Does std::map::iterator return a copy of value or a value itself?

前端 未结 4 594
生来不讨喜
生来不讨喜 2021-02-03 23:25

I\'m trying to create a map inside a map:

typedef map inner_map;
typedef map outer_map;

Will I be ab

4条回答
  •  花落未央
    2021-02-03 23:33

    I want to add a follow up answer to this question for people using C++11 iterators...

    The following code:

    std::map m({{"a","b"},{"c","d"}});
    for (auto i : m)
    {
        std::cout << i.first << ": " << i.second << std::endl;
    }
    

    does copy the key and value since "auto" is a value by default, not a const reference (at least that's how it behaves clang 3.1).

    Additionally, the code:

    std::map m({{"a","b"},{"c","d"}});
    for (const std::pair& i : m)
    {
        std::cout << i.first << ": " << i.second << std::endl;
    }
    

    also copies the key and value since the correct code should be:

    std::map m({{"a","b"},{"c","d"}});
    for (const auto& i : m)
    {
        std::cout << i.first << ": " << i.second << std::endl;
    }
    

    or

    std::map m({{"a","b"},{"c","d"}});
    for (const std::pair& i : m)
    {
        std::cout << i.first << ": " << i.second << std::endl;
    }
    

提交回复
热议问题