Iterating over an STL map

  • Thread starter Thread starter Bob Altman
  • Start date Start date
B

Bob Altman

Hi all,

I read somewhere that the STL map class stores entries internally sorted by the
key. I wrote a small test program (below) that verifies that iterating through
the map returns entries with ascending key values. My question is: Is this
guaranteed behavior or is it just the current implementation which might change
in the future?

TIA - Bob

--- Code example ---

#include "stdafx.h"
#include <map>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
map<int, string> myMap;

myMap[2] = "2";
myMap[5] = "5";
myMap[1] = "1";
myMap[3] = "3";
myMap[6] = "6";

for (map<int, string>::iterator it = myMap.begin();
it != myMap.end(); it++)
{
cout << it->first << " : " << it->second.c_str() << endl;
}

return 0;
}
 
Bob said:
Hi all,

I read somewhere that the STL map class stores entries internally sorted by the
key. I wrote a small test program (below) that verifies that iterating through
the map returns entries with ascending key values. My question is: Is this
guaranteed behavior or is it just the current implementation which might change
in the future?

Bob:

It is guaranteed.
 
I read somewhere that the STL map class stores entries internally sorted by the
key. I wrote a small test program (below) that verifies that iterating through
the map returns entries with ascending key values. My question is: Is this
guaranteed behavior or is it just the current implementation which might change
in the future?

I'd expect it to be guaranteed.

The sorting is done by the traits object - and defaults to less<Key>,
but if need be you can always specify your own.

Dave
 
David Lowndes said:
I'd expect it to be guaranteed.

The sorting is done by the traits object - and defaults to less<Key>,
but if need be you can always specify your own.

Dave

Many thanks to both Davids! - Bob
 
Back
Top