在C ++中使用自定义结构作为map的索引时,“二进制表达式的无效操作数”

Col*_*iot 2 c++ sorting stl

代码:

struct Tag {
    std::string left_tag, right_tag;
};
Run Code Online (Sandbox Code Playgroud)

当我尝试使用时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.
Run Code Online (Sandbox Code Playgroud)

一连串的stl错误让我感到震惊。

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

Cor*_*mer 5

您需要定义一个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);
    }
};
Run Code Online (Sandbox Code Playgroud)

这将定义小于运算符以对两个Tag实例进行排序。就像上面的示例中所写的那样,将按排序left_tag,然后按排序right_tag