Use of for_each on map elements

前端 未结 11 727
北荒
北荒 2021-01-30 10:29

I have a map where I\'d like to perform a call on every data type object member function. I yet know how to do this on any sequence but, is it possible to do it on an associativ

11条回答
  •  醉梦人生
    2021-01-30 11:12

    C++11 allows you to do:

    for (const auto& kv : myMap) {
        std::cout << kv.first << " has value " << kv.second << std::endl;
    }
    

    C++17 allows you to do:

    for (const auto& [key, value] : myMap) {
        std::cout << key << " has value " << value << std::endl;
    }
    

    using structured binding.

    UPDATE:

    const auto is safer if you don't want to modify the map.

提交回复
热议问题