简体   繁体   中英

c++ stl map storage and memory usage

I understood that when inserting new entry, stl map will copy construct and store value instead of pointer or reference.

However, I am confused by the following sample code:

int main( int argc, char** argv ){
    map<int, vector<int> > m;
    for(int i=0;i<10; i++){
        m[i] = vector<int>();
    }
    cout<<sizeof(m)<<endl;
    cout<<m[1].size()<<endl;
    for(map<int, vector<int> >::iterator it=m.begin(); it!=m.end(); it++){
        it->second.push_back(1);
        it->second.push_back(1);
        it->second.push_back(1);
    }
    cout<<sizeof(m)<<endl;
    cout<<m[1].size()<<endl
}

The outputs are

48
0 
48  
3

Why the size of the map is unchanged even though I am changing the values of the map?

Firstly, if by size you mean the number of entries in the map, you need to use m.size() rather than sizeof(m) . The latter measures the size (in bytes) of the std::map object, which isn't where the actual entries are stored. So that size won't change, no matter how many entries you add.

Secondly, your code doesn't actually add any new entries to the map. It only adds entries to some of the vectors in the map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM