Divya Kiran Kadiyala
Divya Kiran Kadiyala

Reputation: 75

Why is the second element being printed in map?

In the below code, why element 2 is being returned instead of element 1 when begin() is used ? Could somebody please explain this ?

int main()
{
    map <string, int> name;

    // Adding the contents into map

    name["David"]   = 1;
    name["Charlie"] = 2;
    name["Robert"]  = 3;

     map<string, int>::iterator i1 =name.begin(); 

        cout << "The first element is : " << (*i1).first << "The second     
    element is "<<(*i1).second<<endl;

    }

In the output I am getting as

The first element is : Charlie The second element is 2

Upvotes: 0

Views: 50

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137810

std::map is a sorted container. The values which get sorted are of type std::pair< std::string, int >. So the first item is the pair {"Charlie", 2}. It happens that the members of pair are named first and second.

So std::pair< std::string, int >{"Charlie", 2}.first is "Charlie", and
std::pair< std::string, int >{"Charlie", 2}.second is 2.

first and second are not referring to the sorted sequence of the map.

Upvotes: 1

Eric
Eric

Reputation: 19863

When you add items to the map, they automatically get sorted by keys. This means that the map stores your item by the alphabetical order of the key. In that case, Charlie gets first spot, then David and finally Robert.

Should you change Charlie for John, then David would be stored first. I'm not entirely sure of what you intend to do with this, but it would seem that your numbers should be your keys instead

Upvotes: 5

Related Questions