std :: map需要比较器的operator()是const吗? [英] Does std::map require the comparator's operator() to be const?

查看:270
本文介绍了std :: map需要比较器的operator()是const吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在OS X 10.8上使用libc ++时,以下代码无法使用XCode 4.5的clang ++进行编译:

The following code fails to compile with XCode 4.5's clang++ when using libc++ on OS X 10.8:

#include <map>
#include <string>

class Foo {
public:
  explicit Foo(int val_) : val(val_) {}
  int val;
};

struct FooComparator {
  bool operator()(const Foo& left, const Foo& right) {
    return left.val < right.val;
  }
};

int main(int argc, char* argv[]) {

  std::map<Foo, std::string, FooComparator> m;

  Foo f(4);
  m[f] = std::string("four");

  return 0;
}

错误:

broken.cpp:11:8:注意:候选函数不可行:'this'argument
类型为'const FooComparator',但
方法未标记为const bool如果我关闭libc ++并使用libstdc ++构建,那么所有的都是()()(const Foo& left,const Foo& right){

broken.cpp:11:8: note: candidate function not viable: 'this' argument has type 'const FooComparator', but method is not marked const bool operator()(const Foo& left, const Foo& right) {

好。显然,我可以通过使用FooComparator :: operator()const解决这个问题,但我想知道这是否是一个问题,libc ++太严格,或者标准(C ++ 03和C ++ 11 )实际上要求比较器的operator()是const(在这种情况下,它与libstdc ++一起工作的事实是一个幸福的事故)。

If I turn off libc++ and build with libstdc++ then all is well. Obviously, I can work around this by making FooComparator::operator() const, but I'd like to understand whether this is a problem with libc++ being too strict, or whether the standard (both C++03 and C++11) does in fact require that the comparator's operator() be const (in which case the fact that it works with libstdc++ is a happy accident).

推荐答案

好吧,是的:比较器是映射本身的子对象,可能是一个方法或另一个方法(也许是成员;通常是一些内部实现类的基类)。如果你有一个对映射的常量引用,比较器仍然需要可用于查找,所以操作符需要 const

这篇关于std :: map需要比较器的operator()是const吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆