【问题标题】:Overloading the + operator for combining two dictionaries that use vectors重载 + 运算符以组合两个使用向量的字典
【发布时间】: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


【解决方案1】:

std::unique 调用元素的operator== 来判断元素是否相同。您需要为Pair 定义operator==。错误消息甚至告诉您它正在尝试在两个 Pairs 上执行 == 并且失败了。

请注意,std::unique 仅删除 连续 个重复项。如果您的容器未排序(如果您将两个向量连接起来),那么您可能仍然有此检查未检测到的非连续重复项。

使用排序容器似乎是一个更好的主意,并进行排序合并而不是串联。 map 在这里似乎是一个更好的数据结构。

【讨论】:

  • 谢谢!我没有使用 map 的原因是因为我们不允许将它用作此分配的容器。我们必须使用向量或字符数组。我将尝试对向量进行排序,然后调用 unique 并处理 pair == 运算符。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-05-10
  • 2023-03-24
  • 2010-12-13
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多