C++ map from object key to object value

Description

C++ map from object key to object value

#include <iostream> 
#include <map> 

using namespace std; 

class MyClass { //from  w w w  .jav  a 2  s. c  om
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; 
}



PreviousNext

Related