Reputation: 795
For example map1 is gaving values 1 to 10 with some address(begin to end). i want to have values 10 to 1 with corresponding address in map2(begin to end)
map<long , int* > v;
map<long , int* > rv;
int i,a[10];
for(i=0; i<10; i++)
{
a[i] = i+1;
v.insert(pair<long, int *>(i+1,&a[i]));
}
itr = v.begin();
while(itr != v.end())
{
cout << itr->first << " "<<itr->second;
cout << endl;
itr++;
}
rv.insert(v.rbegin(),v.rend());
cout << "copied array: "<<endl;
itr = rv.begin();
while(itr != rv.end())
{
cout << itr->first << " "<<itr->second;
cout << endl;
itr++;
}
i tried above one but am getting values 1 to 10 only..my expected values 10 to 1. please help me to find out....
Upvotes: 2
Views: 397
Reputation: 35716
This is impossible because std::map
is ordered associative container. If you want to preserve order of insertion use other containers such as std::list
or std::vector
.
Upvotes: 1
Reputation: 726599
STL map is an ordered container. The order of items that you get during the iteration is independent of the order in which you insert the items into the container.
The order of iteration is determined by two things:
Compare
class passed as the template parameter to the map
You can iterate the map in reverse order (your code snippet shows that you already know how it is done). The performance penalty for reverse-iterating a map, if any, is negligible. You can also provide a non-default Compare
(std::greater<long>
instead of the default std::less<long>
) to have the default order of iteration altered.
Upvotes: 8
Reputation: 2196
Maps sort by increasing value (as dictated by operator< ), so no matter how you insert the elements, they will be returned in sorted order. You are certainly doing the insertion in reverse, but every element placed is being duly sorted into proper ascending order.
Upvotes: 0