Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to get an object in std::map by reference?

Tags:

c++

reference

map

I have a map like this

map<int,object> objmap;
object& obj = objmap.find(num)->second;
object& obj2 = objmap[num];

Whatever changes I make in the object have to be reflected on the map. Similar thing cant be done in a vector as it changes location of objects when it wants more space. Is it safe to do it in a std::map? and is it advisable? The second version gives an error as my object doesn't have an empty constructor. If I declare an empty constructor doing nothing, will the two lines will work the same way?

like image 260
balki Avatar asked Dec 29 '10 15:12

balki


People also ask

Does map insert copy or reference?

Yes -- when you insert an item into an std::map, you pass it by value, so what it contains is a copy of what you passed.

Can you store references in a map C++?

The reason why you can't store them in a map is purely semantic; you have to initialize a reference when it's created and you can't change it afterward anymore. This doesn't mesh with the way a map works.

Are std :: maps ordered?

Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.

What is std::map used for?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.


1 Answers

So long as the object in question isn't removed from the map, then yes it is safe. Once inserted into a map objects don't move around even if other elements are added or removed.

object& obj = objmap.find(num)->second;

This is potentially dangerous unless you are sure that an element with key num actually exists in the map. If you are not sure, you could use the overload of insert that returns an iterator and a bool which indicates whether a new element was inserted or an element with the given key was already present in the map.

E.g.

object& obj = objmap.insert( std::make_pair(num, object(arg1, arg2, argN)) ).first->second;
like image 54
CB Bailey Avatar answered Oct 05 '22 18:10

CB Bailey