我编写了一个函数来计算两个集合的并集。
我遇到了几个编译错误,我相信这部分是由于我如何制作 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&)'
Insert 和 find 工作正常,我能够在我的 remove 函数和其他一些函数中使用 insert 和 find 函数,为什么我不能在这里使用它们?
最佳答案
在你的行中
StringSet StringUnion = make_unique<string[]>(arrSize);
RHS 使用 c++14 construct that takes an std::size_t
, and returns an std::unique_ptr<std::string>
internally pointing to an array .
然而,LHS 是一个 StringSet
目的。
您没有定义采用这种类型的构造函数,所以这是个问题。
查看您的代码,StringSet
确实有 std::unique_ptr<std::string>
成员,所以你可以添加一个构造函数来获取这样的对象,并从中初始化成员。但是,不清楚这样一个 ctor 有什么好处,因为您已经有了一个 ctor
StringSet(int capacity);
基本上已经做了同样的事情。
正如 Leon 所写,你应该只使用这个而不是你拥有的那一行
StringSet StringUnion(arrSize);
关于C++ - SetUnion 函数的字符串数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39763094/