【问题标题】:copy_if with map whose value is also a std::paircopy_if 与 map 其值也是一个 std::pair
【发布时间】:2021-06-09 13:25:00
【问题描述】:

我有一个输入映射inMap,其类型为map<double, pair<int, double>>

我正在尝试通过copy_if 过滤此地图,如下所示:

map<double, pair<int, double>> outMap;
copy_if(inMap.begin(), inMap.end(), outMap.begin(), [](pair<double, pair<int, double>> item) {return (true) ;} // I have simplified the predicate 

但是,在编译时,我收到以下错误:

error: use of deleted function 'std::pair<const double, std::pair<int, double>>& std::pair<const double, std::pair<int, double>>::operator=(const std::pair<const double, std::pair<int, double>>&)

【问题讨论】:

  • 你注意到这对中的const了吗(对于关键部分)?
  • 您不能改变 const 对象...std::inserter(outMap, outMap.end()) 可能会有所帮助。 (不确定你想要什么)

标签: c++ stl std-pair


【解决方案1】:

std::map 的迭代器不适合与copy_if 一起使用,因为该算法只会尝试分配整个值。但是,std::map 的迭代器的值类型为std::pair&lt;const K, V&gt;,这意味着它不可复制赋值。

但是,您可以使用std::inserter 来完成您想要的操作

std::copy_if(inMap.begin(), inMap.end(), std::inserter(outMap, outMap.end()), Predicate);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 2020-08-27
    • 2011-04-18
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多