C++ examples for STL:map
Store object to map and use object as key
#include <iostream> #include <map> using namespace std; class MyClass { /*from w w w. j av a 2 s.co m*/ public: int Item; }; bool operator < (const MyClass & first, const MyClass & second) { return first.Item < second.Item; } int main() { // First try storing the instances map<MyClass, MyClass> instances; MyClass key1 = {10}; // braces notation! MyClass value1 = {20}; MyClass key2 = {30}; MyClass value2 = {40}; instances[key1] = value1; instances[key2] = value2; value1.Item = 12345; cout << instances[key1].Item << endl; instances[key1].Item = 34567; cout << instances[key1].Item << endl; // Next try storing pointers to the instances map<MyClass*, MyClass*> pointers; MyClass key10 = {10}; MyClass value10 = {20}; MyClass key11 = {30}; MyClass value11 = {40}; pointers[&key10] = &value10; pointers[&key11] = &value11; value10.Item = 12345; cout << (*pointers[&key10]).Item << endl; return 0; }