Home > Software design >  how to iterate a unordered map from begin to a certain index not end
how to iterate a unordered map from begin to a certain index not end

Time:07-31

Suppose I have a unordered map of size 5 but I want to run a for loop for index 0 to index 1 then what should be the syntax? I tried this but such error is coming.enter image description here

CodePudding user response:

I believe (without having looked at the images) and just going from your description, this code might do what you want.

int targetIndex = 1;
auto it = yourMap.begin();
for (int i = 0; i < targetIndex;   i,   it)
{
    //Do stuff to your iterator
}

Alternatively:

int targetIndex = 1;
auto end = yourMap.begin();
std::advance(end, targetIndex);
for (auto it = yourMap.begin(); it != end;   it)
{
    //Do stuff to your iterator
}

Of course both these snippets assume, that your targetIndex is smaller than the mapSize.

On a side note, these approaches will work the same on any std container.

CodePudding user response:

This code might help you with your problem.

unorderd_map <string,int> m;
m["hh"]=10;
m["gg"]=20;
m["ff"]=30;
m["jj"]=40;
m["kk"]=50;

for(auto it=m.begin(); it!=m.end() ;it  )
{
       cout<<(*it).first<<" "<<(*it).second<<endl;    //cout<<it->first<<" "<<it->second;
}

The output of the program will be

hh 10

gg 20

ff 30

jj 40

kk 50

  •  Tags:  
  • c
  • Related