user3368506
user3368506

Reputation: 133

Can't get the right answer with c++ STL map

I have wrote a small map test program which is below:

void main()
{
    vector<double> price;
    vector<string> time;

    price.push_back(5.70);
    price.push_back(5.77);
    price.push_back(5.81);
    price.push_back(5.72);
    price.push_back(5.81);

    time.push_back("10:40");
    time.push_back("10:43");
    time.push_back("10:44");
    time.push_back("10:46");
    time.push_back("10:48");

    map<double,string> myMap;

    for (int i=0 ; i<price.size() ; i++)
    {   myMap[price[i]] = time[i]; }

    for (int i=0 ; i<price.size() ; i++)
    {   
        if (price[i] == 5.81)
        { cout << myMap[price[i]] << endl; }
    }
}

My expect outputs should be:

10:44
10:48

But the outputs I get is :

10:48
10:48

I don't know why it is wrong.

Upvotes: 1

Views: 242

Answers (4)

Jaffa
Jaffa

Reputation: 12719

From the documentation

Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order.

In a map, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key.

So you can only have one value per key, which is why it printed two time the same value.

Also, you can replace this portion of your code:

for (int i=0 ; i<price.size() ; i++)
{   
    if (price[i] == 5.81)
    { cout << myMap[price[i]] << endl; }
}
// by
cout << myMap[5.81] << endl;

It's more or less the same, if you don't consider the problem with double keys.

Upvotes: 0

Avery
Avery

Reputation: 2293

Note the Unique keys section of the map specification.

Unique keys
No two elements in the container can have equivalent keys.

This means that for each unique key (in your case, 5.81), there can only be one value: the last one set (10:48). For non-unique maps, use multimap

For discussion on the difference between multimap and map: see this

Upvotes: 2

αλεχολυτ
αλεχολυτ

Reputation: 5060

On a last iteration in first cycle you are updating myMap[5.81] previously added 2 iteration above (not add new element). Consider using std::multimap

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234875

myMap can only store one value per key: the key 5.81 is duplicated.

You are overwriting the value "10:44" with your subsequent insertion of 5.81 -> "10.48".

If you want duplicate values for a single key then use std::multimap.

(Also, beware of using floating point types as keys. You'll hit problems with floating point comparison.)

Upvotes: 1

Related Questions