将函数应用于std::map值,其中包含for each和lambda函数

Applying a function to an std::map values with for each and lambda fucntion

本文关键字:函数 for 包含 each lambda std 应用于 map      更新时间:2023-10-16

我想这样做:

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_typestd::pair<const std::string, bool>>。您的代码中缺少const

既然您清楚地使用C++11,为什么不使用范围进行循环和自动类型推导呢?

for(auto& e: mapTrafficLights) {
    e.second = false;
}