Map and files c++

I want mymap to have capacity for 3 elements, if I keep inserting elements that will erase the last one entered for example.. Insert element and write into the file

typename map <string, pair<T,int> > ::iterator i = mymap.find(key);

file.write(reinterpret_cast<const char*>(&i), sizeof(i));

this works, but when i delete an element from mymap its deleted from file too.

i = mymap.find(last.first);
mymap.erase(i);

Why?

Upvotes: 1

Views: 63

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106126

The data managed by a std::map<> object is not embedded directly in the std::map<> object - instead, it's dynamically allocated and the std::map<> object contains pointers to parts of the data so it can start a search. When you file.write you're only writing out the management object and not the nodes - that will never persist the data. After:

std::map<std::string, std::pair<T, int>> mymap;
mymap.emplace("one", {1.0, 1});
mymap.emplace("two", {2.0, 2});

You might imagine the memory areas in use and the pointers between them like this:

mymap:{size=2; p_root_=&MMM; p_least_=&AAA; p_greatest_=&ZZZ;}
                          |             /                /
...on the heap...      +--|-------------        ---------
                       |  v                    /
                       |  MMM                 /
                       v /   \               /
                       ZZZ   AAA<-----------/

If you want to have a container that remembers the last 3 values, consider using a circular buffer (or if you're not overly concerned about performance - even easier, a std::deque<>), though you'll then have to store the keys and values and manually search over the 3 values to find a match on a key.

Upvotes: 1

Related Questions