Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is it possible to use a reference as the value in a map?

Tags:

c++

reference

map

Is it possible to use a reference as the value in a standard map container in C++?
If not - why not?

Example declaration:

map<int, SomeStruct&> map_num_to_struct;

Example usage:

...
SomeStruct* some_struct = new SomeStruct();
map_num_to_struct[3] = *some_struct;
map_num_to_struct[3].some_field = 14.3;
cout<<some_struct.some_field;
...

I would expect to see 14.3 printed...

like image 285
Jonathan Livni Avatar asked Nov 21 '10 17:11

Jonathan Livni


People also ask

Can you pass a map by reference?

To answer your question, passing a map value by reference will not cause problems.

Can you use references in C?

No, it doesn't. It has pointers, but they're not quite the same thing. For more details about the differences between pointers and references, see this SO question.

How do you give a value on a map?

HashMap put() Method in Java HashMap. put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value.

Can we equate maps in C++?

The C++ function std::map::operator== tests whether two maps are equal or not.


2 Answers

No. STL container value types need to be assignable. References are not assignable. (You cannot assign them a different object to reference.)

like image 168
sbi Avatar answered Sep 23 '22 02:09

sbi


No, it's not. You can use pointers as the value type, though.

like image 28
Stuart Golodetz Avatar answered Sep 26 '22 02:09

Stuart Golodetz