As I known, map value is initialized by NULL(0). However, Below code is works well without any allocation. How is this code work?
#include<bits/stdc++.h>
using namespace std;
struct stuc{
map<string, stuc> mp;
int cnt;
}root;
int main() {
stuc* u = &root;
stuc* v = &(u->mp["test"]); // how to allocate?
cout << v->cnt << endl;
return 0;
}
>Solution :
If you access a map with the [] operator like in
&(u->mp["test"])
there is a new key value pair allocated, default initialized, and inserted into the map if the element does not already exists [1]. In your program that is exactly what happens. The map does not already have an key "test". Thus a new value is default constructed. Because you did not define a custom default constructor for your stuc struct, all its members are default initialized (mp = {} and cnt = 0). This is the reason why you get 0 if you read the cnt member of the newly created value.
[1] https://en.cppreference.com/w/cpp/container/map/operator_at