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

时间:2015-05-11 13:09:33

标签: 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.

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

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

1 个答案:

答案 0 :(得分: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);
    }
};

这将定义less-than运算符以对两个Tag实例进行排序。如上例所示,这将按首选left_tag,然后right_tag进行排序。