c++ - 在 C++ 中使用自定义结构作为映射索引时出现 "invalid operands to binary expression"

标签 c++ sorting stl

代码:

struct Tag {
    std::string left_tag, right_tag;
};

当我尝试使用 this->_tags[__tag] = true; 时,出现错误:

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__functional_base:63:21: error: invalid operands to binary expression ('const Tag' and 'const Tag')
        {return __x < __y;}
                ~~~ ^ ~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/map:1207:17: note: in instantiation of member function 'std::__1::less<Tag>::operator()' requested here
            if (__tree_.value_comp().key_comp()(__k, __nd->__value_.__cc.first))
                ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/map:1376:36: note: in instantiation of member function 'std::__1::map<Tag, bool, std::__1::less<Tag>, std::__1::allocator<std::__1::pair<const Tag, bool> > >::__find_equal_key' requested here
    __node_base_pointer& __child = __find_equal_key(__parent, __k);
                                   ^
/Users/xxx/GitHubWorking/MarkupUtils/Syntax.h:69:20: note: in instantiation of member function 'std::__1::map<Tag, bool, std::__1::less<Tag>, std::__1::allocator<std::__1::pair<const Tag, bool> > >::operator[]' requested here
        this->_tags[__tag] = true;
                   ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/utility:419:1: note: candidate template ignored: could not match 'pair<type-parameter-0-0, type-parameter-0-1>' against 'const Tag'
operator< (const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
^
1 error generated.

我对一系列长 STL 错误感到震惊。

根据最深的错误,这是由于使用const标签引起的,但我的代码中似乎没有任何错误。

最佳答案

您需要定义一个 operator<例如

struct Tag
{
    std::string left_tag, right_tag;

    bool operator< (const Tag& rhs) const
    {
        return this->left_tag < rhs.left_tag ||
               (this->left_tag == rhs.left_tag && this->right_tag < rhs.right_tag);
    }
};

这将定义小于运算符来对两个 Tag 进行排序实例。正如上面的示例中所写,这将按首选 left_tag 进行排序。 ,然后right_tag .

关于c++ - 在 C++ 中使用自定义结构作为映射索引时出现 "invalid operands to binary expression",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30168553/

相关文章:

c++ - NetBeans配置

java - 为什么 binarySearch 需要排序数组?

c++ - 在 2 个对象之间共享容器的提示?

c++ - 二维数组重载

c++ - 如何解析文件内容并加载到 map 中

c++ - 成员引用基类型不是结构或 union

C++ DirectX - 对 2D 网格进行纹理化

c++ - 带有可选参数的 Poco 选项

C#: double 的 Array.Sort 方法?

multithreading - Clojure 中的多线程合并排序算法