【发布时间】:2014-11-09 20:28:07
【问题描述】:
我是 C++ 的初学者,我一直在尝试解决这个问题,但我无法解决这些错误。
我需要做的是为我创建的一个名为 Dictionary 的类重载 + 运算符。字典使用向量来存储键/值对,我在此处发布了一个类 Pair:
class Pair {
private:
string key;
int value;
public:
Pair(string k="", int v=0){key=k; value=v;};//should we be allowed to have 0,0 pairs?
~Pair(){};
string getKey(){return key;};
int getValue(){return value;};
};
这是我的 Dictionary 类和 + 运算符的重载:
class Dictionary{
std::vector<Pair> dic;
public:
Dictionary(){};
~Dictionary(){};
Dictionary operator +(const Dictionary &vec2){
Dictionary combined;
combined.dic.reserve( combined.dic.size() + vec2.dic.size() ); // preallocate memory
combined.dic.insert( combined.dic.end(), combined.dic.begin(), combined.dic.end() );
combined.dic.insert( combined.dic.end(), vec2.dic.begin(), vec2.dic.end() );
//dic.insert( dic.end(), vec2.dic.begin(), vec2.dic.end() );
if (unique( combined.dic.begin(), combined.dic.end() )){
return combined;
}
else{
cout<<"ERROR: the dictionaries each contain the same key!"<<endl;
}
}
我想要实现的是,当我使用 + 将两个字典添加在一起时,如果没有重复的键/值对,它们将组合成一个大字典。 (这就是 unique 的用途)如果有重复,则不要添加它们,而只是打印出一个错误。
当我编译时,我从 algorithm.cc 得到这个错误: “/opt/local/solstudio12.2/prod/include/CC/Cstd/algorithm.cc”,第 205 行:错误:操作“Pair == Pair”是非法的。 “/opt/local/solstudio12.2/prod/include/CC/Cstd/algorithm”,第 482 行:其中:在实例化“std::adjacent_find(Pair*, Pair*)”时。 “/opt/local/solstudio12.2/prod/include/CC/Cstd/algorithm”,第 482 行:其中:从非模板代码实例化。 检测到 1 个错误。
我可以就如何解决这个问题和解决这个问题提供一些建议吗?非常感谢!
【问题讨论】:
-
听起来像
map会比vector更合适,至少对我而言。 -
重载的
operator!=对我来说似乎很奇怪,因为您检查其中的平等,而不是不平等。 -
您好 Joachim,我删除了操作符!= 但我仍然遇到同样的错误。我没有打电话给那个运营商!=所以暂时它没有给我带来问题。我无法让 Dictionary 的 + 运算符正确,你知道为什么会这样吗?
-
也许你需要为
Pair写一个operator ==? -
这一行似乎有点奇怪
combined.dic.insert( combined.dic.end(), combined.dic.begin(), combined.dic.end() );你可能想插入dic而不是combined.dic。
标签: c++ operator-overloading overloading stdvector