Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Storing references to values in std::map

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.

like image 223
Fire Lancer Avatar asked Jul 01 '09 11:07

Fire Lancer


People also ask

How are values stored in map C++?

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.

Can value in map Be pair in C++?

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.

Can a map store duplicate values C++?

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.

How are references stored in C++?

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.


2 Answers

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.

like image 53
Johannes Schaub - litb Avatar answered Nov 12 '22 08:11

Johannes Schaub - litb


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.

like image 22
CiscoIPPhone Avatar answered Nov 12 '22 07:11

CiscoIPPhone