将函数应用于std::map值,其中包含for each和lambda函数
Applying a function to an std::map values with for each and lambda fucntion
我想这样做:
std::map<std::string, bool> mapTrafficLights;
mapTrafficLights.emplace("RED", true);
mapTrafficLights.emplace("GREEN", true);
mapTrafficLights.emplace("ORANGE", true);
std::for_each(mapTrafficLights.begin(), mapTrafficLights.end(), []
(std::pair<std::string, bool>& it) {it.second = false; });
std::for_each(mapTrafficLights.begin(), mapTrafficLights.end(), [](std::pair<std::string, bool> it) {std::cout << it.first << " " << ((it.second) ? "ON" : "OFF") << std::endl; });
如果我保留引用符号"&",则最后一行之前的行不会编译,但当我删除它时,它会编译,但不会更新映射的值。我想将所有布尔值设置为false,但使用STL工具在一行中使用这种风格的代码。
映射元素的类型为std::pair<const std::string, bool>
。这意味着您的lambda签名将需要类型转换为std::pair<std::string, bool>
,需要创建一个临时对象。并且不能将非常量左值引用绑定到临时值。你需要
std::for_each(mapTrafficLights.begin(), mapTrafficLights.end(),
[] (std::pair<const std::string, bool>& it) {it.second = false; });
^^^^^
或者,使用地图的value_type
。
typedef std::map<std::string, bool> str_bool_map;
std::for_each(mapTrafficLights.begin(), mapTrafficLights.end(),
[] (str_bool_map::value_type& it) {it.second = false; });
请注意,对于可变范围,使用std::transform
更为惯用。然而,基于距离的循环可能是最简单的解决方案:
for (auto& p : mapTrafficLights) p.second = false;
std::map<std::string, bool>
的value_type
是std::pair<const std::string, bool>>
。您的代码中缺少const
。
既然您清楚地使用C++11,为什么不使用范围进行循环和自动类型推导呢?
for(auto& e: mapTrafficLights) {
e.second = false;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- C++函数模板需要 &for 数组参数
- 有没有办法将 for 循环结果返回到像三元运算符这样的函数中?
- 创建函数变体向量时"No matching function for call"错误
- 如果子类中没有构造函数方法,则错误"no matching function for call to 'LGame::LGame(String&)'"
- 虚拟函数调用的性能作为 for 循环中的上限
- constexpr 函数中的 for 循环无法使用 MSVC 19.23 进行编译
- 函数中的"pragma omp parallel for"在另一个并行循环中调用函数时无效
- 找不到如何创建使用指针、字符和 for 函数组合的程序
- 这个基于范围的'for'语句需要一个合适的函数,但找不到任何函数
- For 和 while 循环在全局定义的函数中不起作用
- c++ 中的 range-for 会调用项的复制构造函数吗?
- 计算使用 C++ std 函数而不是 for 循环的大 O
- 调用模板函数的问题"No matching function for call"参数:迭代器、对象函数
- 使用 std::vector<Particle> 粒子;函数 .at() 不能与迭代器一起使用,它作为 for 循环中的参数
- lambda deleter for Unique_ptr导致编译错误与函数
- 为什么我的 for 循环在我的 void 函数中不起作用
- 无法在 for 循环中的 pow 函数上输出答案
- C++ - 计算"for"函数中的平均值