Am I right in assuming that adding/removing elements to an std::map does not effect the other elements (ie cause them to be relocated in memory) and so that the following is safe:
I looked at various sites with info on the container but only found out about the cases where iterators are invalidated, which I already know...
std::map<std::string,std::string> map;
PopulateMap(map);
std::string &a= map["x"];
AddMoreData(map);
RemoveRandomKeysExceptX(map);
map["x"] = "foo";
std::cout << a << " " << map["x"] << std::endl;//prints "foo foo"
a = "bar";
std::cout << a << " " << map["x"] << std::endl;//prints "bar bar"
I tested some similar code on VC9, which seems to work however that doesn't mean I didn't just get lucky or that it doesn't vary across compilers.
Maps are associative containers that store elements in a combination of key values and mapped values that follow a specific order. No two mapped values can have the same key values. In C++, maps store the key values in ascending order by default. A visual representation of a C++ map.
A C++ map is a way to store a key-value pair. A map can be declared as follows: #include <iostream> #include <map> map<int, int> sample_map; Each map entry consists of a pair: a key and a value.
C++ Software Engineering Multi-map in C++ is an associative container like map. It internally store elements in key value pair. But unlike map which store only unique keys, multimap can have duplicate keys.
Reference is one type of variable stored on stack because of there is need to perform operation on them where object stored on heap. In c++ references are stored in stack surely.
The Standard is clear on this in 23.1.2/8
about associative containers
The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements. quote taken from sgi docs.
If the iterators are guaranteed not to change then the values they point at also cannot change.
naveen previously had an answer that was similar to this. Unless there is a mistake in my logic what you are doing is safe.
Edit 2: See point 3 in sgi docs to see how getting a value from operator [] is the same as getting the value from an iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With