Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define a map whose key is a structure?

and how can I do it in C++?

like image 427
Ankit Avatar asked Oct 14 '10 17:10

Ankit


People also ask

Can a map have keys of different types?

On some occasions, we might want to use a map where the keys are not always the same type. For example, if we change our ID types from Long to String, then our data store will need to support both key types – Long for the old entries and String for the new ones.

What is a map structure?

A Map is a type of fast key lookup data structure that offers a flexible means of indexing into its individual elements.

Can a map be a key?

You can't use a Map as a key but you can use it as a value. To explain further, since you are likely to be adding to the HashMap the key will not remain constant and thus will no longer serve it's purpose as a key.

Can HashMap have object as key?

A simple thumb rule is to use immutable objects as keys in a HashMap . because: If it were mutable, then the hashcode() value or equals() condition might change, and you would never be able to retrieve the key from your HashMap .


1 Answers

You can use any type as a map key, as long as it implements an operator< (plus the usual copy-and-assign requirements for values stored in containers).

For instance:

struct example { int x; }

bool operator < (const example &l, const example &r) { return l.x < r.x; }

std::map<example, int> values;

Alternatively, you may provide a comparison function as the third argument of the map template instead of defining operator<. More details here (parameter Compare).

like image 193
Victor Nicollet Avatar answered Oct 05 '22 07:10

Victor Nicollet