Iterating over an STL map

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;
}
 
D

David Wilkinson

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.
 
D

David Lowndes

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
 
B

Bob Altman

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top