c++ - 在 C++ 中使用自定义字符串类作为映射键值

标签 c++ string dictionary key operator-overloading

当我尝试使用我的自定义字符串类作为键值时,我看到了这个错误

undefined reference to `operator<(DSString const&, DSString const&)'

我已经重载了 < 运算符,但它只允许我使用一个参数来执行此操作,而不是两个。我读到一个与此类似的问题,但我无法找到任何解决方案。

bool DSString::operator< (const DSString& newData){
    bool lessThan = true;
    int counter = 0;
    int dataLetter = 0;
    int newDataLetter = 0;

    //compare each letter of both Strings until they differ,
    while(dataLetter == newDataLetter && counter < this->length){
        dataLetter = static_cast<int>(data[counter]);
        newDataLetter = static_cast<int>(newData.data[counter]);
         //change bool if char of current stirng is greater
        if(dataLetter < newDataLetter)
            lessThan = true;
        else if (dataLetter > newDataLetter)
            lessThan = false;
    }

    return lessThan;
}

最佳答案

您的成员运算符要求左侧(即由 this 指针指定的那一侧)是非 const。将 const 添加到声明中将解决问题:

bool DSString::operator< (const DSString& newData) const;

您对 while 循环的实现不正确:您的运算符返回的值对应于最后的比较结果。一旦发现差异,正确的实现应该立即返回 truefalse;仅当相应位置的字符相同时,循环才应继续。此外,当到达两个字符串中较短 的末尾时,循环应该停止;当 this 字符串用完字符时,您当前的实现将停止,当另一个字符串较短时会导致未定义的行为。

Demo.

关于c++ - 在 C++ 中使用自定义字符串类作为映射键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48738784/

相关文章:

c++ - 关于迭代器和泛型函数的考试题

c - 为什么在程序中两次使用 gets() 来获取两个不同数组的输入即使对于第一个数组也只返回第二个输入?

Python:字典推导式:使用旧字典 id 中的新值创建新字典

python - 提取字典中的值

c++ - 获取 CUDA thrust::transform operator() 函数中的 vector 索引

c++ - 从队列中弹出不同类型项目的运行时开销

c# - C++ 中的枚举类 - 替换 - 在 C# 中

c++ - 将字符串转换为二进制的最快方法?

java - offsetByCodePoints 与整数迭代器

ios - 尝试将值附加到字典