将函数应用于每个和lambda函数的{std :: map值

时间:2015-12-27 14:01:40

标签: c++ stl

我想这样做:

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; });
如果我保留参考符号“&amp;”,那么最后一行之前的行将无法编译但是当我删除它时,它会编译,但它不会更新我的地图的值。我想将所有布尔值设置为false,但是使用STL工具将这种样式的代码放在一行中。

2 个答案:

答案 0 :(得分:6)

地图元素的类型为std::pair<const std::string, bool>。这意味着您的lambda签名需要将类型转换为std::pair<std::string, bool>,这需要创建临时对象。并且您不能将非const左值引用绑定到临时值。你需要

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;

答案 1 :(得分:4)

value_type的{​​p> std::map<std::string, bool>std::pair<const std::string, bool>>。您的代码中缺少const

由于你明显使用的是C ++ 11,为什么不使用range-for循环和自动类型演绎?

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