Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ – structure in map allocation

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading