Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Auto based Ranged for loop vs using pair based Ranged for loop

Tags:

c++

In the below code

#include <iostream>
#include<unordered_map>
#include<string>

int main()
{
    std::unordered_map<std::string,int>m;
    m["1"]=1;
    m["2"]=2;

    for(const std::pair<std::string,int>&p :m)
    {
        std::cout<<&p<<"\n";
        /*0x7fff5fbff068
          0x7fff5fbff068*/
    }

    for(const auto &p :m)
    {
        std::cout<<&p<<"\n";
        /*0x10061e410
         0x10061e3e0*/
    }

}

If I use a normal pair based ranged for loop it shows me same address for both the iteration

0x7fff5fbff068
0x7fff5fbff068

Whereas if I use auto the address changes for both the iteration

/*0x10061e410
  0x10061e3e0*/

Why there is difference in behavior .Isn't both should show different address even in ranged based for loop using pair.

What is the difference between both the ranged for loop

like image 926
Hariom Singh Avatar asked Dec 02 '25 07:12

Hariom Singh


1 Answers

Well, here's the thing. Your two loops don't use the same type of element.

The map iterator returns a reference to std::pair<const std::string, int>1. And your first loop constructs a temporary object out of that (since your std::string is not const qualified). So you aren't printing the address of the pair inside the map in the first loop.

It's not impossible the compiler cleverly uses the same storage to construct the temporary object at every iteration, so you always see the same address printed.


1 You aren't allowed to modify the key via iterator, remember. It will mess up the map invariants.

like image 191
StoryTeller - Unslander Monica Avatar answered Dec 04 '25 23:12

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!