unexpected copies with foreach over a map

后端 未结 3 1388
滥情空心
滥情空心 2020-12-18 21:07

I am trying to loop over the entries of a map, and I get unexpected copies. Here is the program:

#include 
#include 
#include <         


        
相关标签:
3条回答
  • 2020-12-18 21:28

    The value type of map<K,V> is pair<const K,V>; so your loop needs to convert pair<const int,X> to pair<int,X>, copying both the key and the value, to give you a reference to that type.

    Using the correct type (specified explicitly, or deduced with auto) will remove the copies.

    0 讨论(0)
  • 2020-12-18 21:37

    The copies are due to the fact that you are iterating a map but binding the wrong reference type. The value_type for that map is std::pair<const int, X> (note the const). Because they are not the same type, the compiler is creating a temporary and binding the reference.

    You can (probably should) iterator using auto& or const auto& in most cases, which will avoid this kind of issues. If you want spell out the type, you can use the nested value_type or the exact type:

    for (const std::map<int,X>::value_type& r : numbers) {
    // or
    for (const std::pair<const int,X>& r : numbers) {
    

    The preference should be: const auto& r then const std::map<...>::value_type& and then const std::pair<const int, X>&. Note that the further to the right in the list, the more knowledge you are providing and the less you allow the compiler to help you.

    0 讨论(0)
  • 2020-12-18 21:45

    The value_type in a std::map<K, V> is not std::pair<K, V> but rather std::pair<K const, V>. That is, you can't change the key component of the elements. If the compiler finds a request to get a std::pair<K, V> const& from a std::pair<K const, K> const& it uses the conversion constructor of std::pair<...> and creates a suitable temporary.

    I'd recommend using value_type instead to avoid any differences:

    for (std::map<int, X>::value_type const& p: numbers)
        ...
    

    Alternatively you can have the type be deduced:

    for (auto const& p: number)
        ...
    
    0 讨论(0)
提交回复
热议问题