我写了一个函数来计算两组的并集。
我遇到了几个编译错误,我相信这部分是由于我如何制作StringUnion
数组并声明它,但到目前为止我没有做任何事情。
这是我的头文件。
#ifndef StringSet_header
#define StringSet_header
#include <memory>
#include <string>
using std::string;
using std::unique_ptr;
using std::make_unique;
class StringSet{
public:
//create an empty set
StringSet() = default;
StringSet(int capacity);
//copy a set
StringSet(const StringSet &);
StringSet& operator[](const int);
//Insert a string to the set
bool insert(string);
//Remove a string from the set
bool remove(string);
//Test whether a string is in the set
int find(string) const;
//Get the size of the set
int size() const;
//get string at position i
string get(int i) const;
//Return the set union of the set and another StringSet
StringSet setunion(const StringSet&) const;
//Return the intersection of the set and another StringSet
StringSet intersection(const StringSet&) const;
//Return the set diffference of the set and another StringSet
StringSet difference(const StringSet&) const;
//prevent default copy assignment
StringSet& operator=(const StringSet&) = delete;
int NOT_FOUND = -1;
static constexpr int def_capacity {4};
private:
int arrSize {def_capacity};
int currentSize {0};
unique_ptr<string[]> arr {make_unique<string[]>(def_capacity)};
};
#endif
这是我对我的SetUnion
功能的实现。
StringSet StringSet::setunion(const StringSet &Array2) const
{
StringSet StringUnion = make_unique<string[]>(arrSize);
if (currentSize > 0)
{
for (auto i=0; i < currentSize; i++)
{
auto s = arr[i];
StringUnion.insert(s);
}
for (auto i=0; i < Array2.currentSize; i++)
{
auto s = Array2[i];
if (StringUnion.find(s) == NOT_FOUND)
{
StringUnion.insert(s);
}
}
}
else
{
auto result = StringSet();
return result; //return empty StringSet}
}
}
错误:
|error: conversion from 'std::_MakeUniq<std::basic_string<char> []>::__array {aka std::unique_ptr<std::basic_string<char> []>}' to non-scalar type 'StringSet' requested|
error: passing 'const StringSet' as 'this' argument discards qualifiers [-fpermissive]
error: no matching function for call to 'StringSet::find(StringSet&)'
error: no matching function for call to 'StringSet::insert(StringSet&)'
按预期插入和查找工作,我能够在我的删除功能和其他一些功能中使用插入和查找功能,为什么我不能在这里使用它们?