Soham Mafidar
Soham Mafidar

Reputation: 63

Why the std::map storing fewer elements than expected?

Why the map in my code is storing only two elements instead of three?

vector<int> v1 = { 140,229,319 };
vector<int> v2 = { 82,216,326 };
map<int, int> mp;

for (int i = 0; i < v1.size(); i++)
{
    if (v1[i] > v2[i])
    {
        mp.insert({ 1,v1[i] - v2[i] });
    }
    else if (v2[i] > v1[i])
    {
        mp.insert({ 2,v2[i] - v1[i] });
    }
}

cout << mp.size() << endl;

for (auto it = mp.begin(); it != mp.end(); it++)
{
    cout << it->first << " " << it->second << endl;
}

It should store: (1,58) (1,13) (2,7)ideally. But it is storing only (1,58) (2,7). I checked the size and it was showing 2.

Where am I going wrong?

Upvotes: 1

Views: 86

Answers (1)

JeJo
JeJo

Reputation: 32852

First, std::mapis a sorted associative container, which only keeps unique keys. Meaning, what you're expecting is not possible with the std::map.

You should think either with


Where am I going wrong?

Consider the check

if(v1[i] > v2[i])

you have two iteration which satisfy this condition:

140, 229   // v1
82 , 216   // v2

The difference (i.e. v1[index] - v2[index]) between the first two is 58 and the second is 13. In the first iteration, the map get inserted with the (1, 58). In the second iteration it should have (1, 13), but from std::map::insert:

Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key.

Hence it has not been inserted.

Upvotes: 1

Related Questions