0
#include<iostream>
#include<map>
using namespace std;
int main() 
{
    map<int, string> sample;
    for (int i = 5; i > 0; i--)
        sample[i] = 'i' + i;
    map<int, string>::iterator i = sample.begin();
    for (int j = 1; j <= 10; j++) 
    {
        cout << sample[j] << endl;
    }
    for (; i != sample.end(); i++)
        cout << i->first;
    cout << "Size is :" << sample.size();
}

I ran this program to know more about std::map ie I am getting map size as 10 and pls refer the below screenshot of output.

enter image description here

Could someone pls clarify me why std::map is auto extending in invalid loop display function .

Prakash Kumar
  • 79
  • 1
  • 11

2 Answers2

4

std::map::operator [key] is equivalent to (*((this->insert(make_pair(key, mapped_type()))).first)).second, so inserts a default value if element is not present.

You have to use at or find to not insert element in map, or use iterator.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

Could someone pls clarify me why std::map is auto extending in invalid loop display function .

std::map::operator[]

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

P0W
  • 46,614
  • 9
  • 72
  • 119