我想做这个 :
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; });
Run Code Online (Sandbox Code Playgroud)
如果我保留引用符号"&",则在最后一行之前的行将不会编译,但是当我删除它时,它会编译,但它不会更新我的地图的值.我想将所有布尔值设置为false,但使用STL工具将此样式的代码放在一行中.
地图元素的类型是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; });
^^^^^
Run Code Online (Sandbox Code Playgroud)
或者,使用地图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; });
Run Code Online (Sandbox Code Playgroud)
请注意,对于变异范围,使用它更惯用std::transform.但是,基于范围的循环可能是最简单的解决方案:
for (auto& p : mapTrafficLights) p.second = false;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
210 次 |
| 最近记录: |