Initialization of maps

Hi.
How are map variables initialized?cOULD SOMEONE PLEASE EXPLAIN THE FOLLOWING CODE TO ME?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

// accessing mapped values
#include <iostream>
#include <map>
#include <string>

int main ()
{
  std::map<std::string, int> mymap;
/*
  mymap["ali"]= 0;
  mymap["ali2"]= 0;
  mymap["ali3"]=mymap["ali2"];
*/
  std::cout  << ++mymap["ali"] << '\n';
  std::cout << ++mymap["ali2"] << '\n';
  std::cout << ++mymap["ali3"] << '\n';
  std::cout << ++mymap["ali4"] << '\n';

  std::cout << "mymap now contains " << mymap.size() << " elements.\n";
  
  while(1);
  return 0;
}
initialized?
like this
1
2
mymap["ali"] = 23;
mymap["ali2"] = 4;

a key called "ali" will be added with a value of 23.
another key called "ali2" will be added with a value of 4.

to access them you can use a loop.
1
2
3
4
5
auto it = mymap.begin();
for(; it != mymap.end(); it++)
  {
      std::cout << it->first << "-" << it->second << '\n';
  }

we create a value with the beginning of map. the first value.
then we make a for loop to increment that value for as long as its not equal to the ending of the map. the last value.

to access the key we call ->first and to access that keys values we call ->second

then we get
1
2
ali-23
ali2-4


we can also add elements like you did
1
2
3
4
std::cout  << ++mymap["ali"] << '\n';
std::cout << ++mymap["ali2"] << '\n';
std::cout << ++mymap["ali3"] << '\n';
std::cout << ++mymap["ali4"] << '\n';

although you never gave a value to these keys, so by default they are initialized as "1".

now as to what your code does.
we create a map with a key as a string and a value as an integer. this map is called mymap.

it increments the map to add the values "ali" to "ali4". but since youre making a cout call to the key, it prints the VALUE of the key, not the key itself. so since by default the value is 1. it prints 1 four times.

then we print the size of the map which returns 4.
mymap["ali"] returns a reference to the mapped_type (the second argument in the template parameter - in your case, an int). If no previous entry exists in the map, then one is inserted using the default constructor (for a class) or 0 (for a base type). I don't remember the syntax for doing this sort of initialization. Someone help me out.

So the first time you call mymap["ali"], it inserts a new entry mapping "ali" -> 0 and returns a reference to it. After that it returns a reference to the existing value.

That means ++mymap["ali"] is pre-incrementing the reference, so it pre-increments the value in the map.
Topic archived. No new replies allowed.