Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a reference type be used as the key type in an STL map

Can I construct an std::map where the key type is a reference type, e.g. Foo & and if not, why not?

like image 349
davetapley Avatar asked Nov 25 '09 10:11

davetapley


People also ask

Can we use any user defined data type as a key in map in C++?

We can use any of the data types as the data type of the key of the map. Even a user-defined data type can be used as key data type.

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.

Which data structure is used by map in STL?

List: A list in STL is used to implement the doubly-linked lists. Unlike an array, lists are used to store the data, which is not contiguous.


2 Answers

According to C++ Standard 23.1.2/7 key_type should be assignable. Reference type is not.

like image 197
Kirill V. Lyadvinsky Avatar answered Sep 19 '22 18:09

Kirill V. Lyadvinsky


No, because many of the functions in std::map takes a reference to the keytype and references to references are illegal in C++.

/A.B.

like image 20
Andreas Brinck Avatar answered Sep 17 '22 18:09

Andreas Brinck