What is the difference in using and not using "&" in range-based for loops usually iterating over maps in C++?

87 Views Asked by At

for (auto& it: map_name) { // __ some _ code __ }

I want to know whether using & makes any big difference and can we use it to directly access second element of the iterator?

1

There are 1 best solutions below

3
On

Iterate over maps using structured bindings like this, the references will avoid copying classes. The const is added because a print loop should never modify anything in the map.

#include <map>
#include <iostream>

int main()
{
    std::map<int, int> map{ {1,2}, {2,5}, {3,7} };

    for (const auto& [key, value] : map)
    {
        // key will be a const reference to the key at the current position in the map
        // value will be a const reference to the value at the current position in the map
        std::cout << key << ", " << value << "\n";
    }

    return 0;
}