【问题标题】:C++11 compilation error while using lambda over map在地图上使用 lambda 时出现 C++11 编译错误
【发布时间】:2013-07-19 17:25:11
【问题描述】:

为什么下面的代码不能编译:

int main() {
  map<int, int> m  = { {1, 2}, {3, 4}};

  auto p = std::min(m.begin(), m.end(), [](const map<int, int>::value_type& a, const map<int, int>::value_type& b)         { return a.second < b.second;});

  std::cout << (p->second) << std::endl;
}

错误是:

X.cc:11:114: note: main()::<lambda(const value_type&, const value_type&)>
X.cc:11:114: note:   no known conversion for argument 1 from 'const std::_Rb_tree_iterator<std::pair<const int, int> >' to 'const value_type& {aka const std::pair<const int, int>&}'

我在这里做错了什么?如果这是一个向量,比如整数向量,我们可以这样做

[](int a, int b){return a<b;}

为什么我们不能在这里做同样的事情?

【问题讨论】:

  • 请具体说明“不工作”。不是在编译吗?那你的错误是什么?它正在运行但崩溃了吗?又是什么错误?

标签: c++ c++11 map lambda


【解决方案1】:

你想要std::min_element 而不是std::min

【讨论】:

    【解决方案2】:

    std::min 将值类型作为前 2 个参数,您正在传递 迭代器

    我猜你想要实现的是地图中最小的元素.second,所以 min_element 就是你需要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 2022-07-15
      • 1970-01-01
      • 2012-10-18
      • 2019-05-19
      • 2018-01-15
      相关资源
      最近更新 更多