-4

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?

  • 2
    i do not think "it" is what you think it is. In your case it is a reference to a key value pair of the map and not an iterator. And if you whould remove & you whould get a copy of the key value pair. – Koronis Neilos Jan 08 '23 at 05:09
  • It is called a reference https://www.learncpp.com/cpp-tutorial/lvalue-references/. An probably it isn't even an iterator so take care with naming your variables too. For iterating over a map also look at https://en.cppreference.com/w/cpp/language/structured_binding it will help you bind to members of iterators to make your code even more readable. – Pepijn Kramer Jan 08 '23 at 05:51

1 Answers1

0

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;
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19
  • Thank You for letting me know the answer. All I have learned here is more than I have ever about the topic. I am sorry that this question is similar to others. I am not smart. Sorry. – Shivansh Thapliyal Jan 09 '23 at 13:51
  • Just give yourself time to learn. C++ has quite a lot of stuff in it, and the hardest part is knowing how C++ should be used today since there are so many examples out there on how C++ was used in the past. If you really want to learn C++ have a look at these https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines you may not understand everything yet. But the idea is that only a subset of C++ should be used for every day use. Oh and keep asking questions. – Pepijn Kramer Jan 09 '23 at 14:29
  • Another site you can always rely on for information is cppreference. E.g. for structured bindings : https://en.cppreference.com/w/cpp/language/structured_binding – Pepijn Kramer Jan 09 '23 at 14:30