kamziro
kamziro

Reputation: 8140

Accessing c++ maps using a different class than the index

Suppose you have a class:

class SomeClass{
   public:
      int x;
      SomeClass(){
         x = rand();
      }

      bool operator<(const SomeClass& rhs) const{
         return x < rhs.x;
      }

};

And then you have this:

map<SomeClass, string> yeah;

Obviously this will work:

yeah[SomeClass()] = "woot";

But is there a way to get something like this:

yeah[3] = "huh";

working? I mean, I tried setting operator<(int rhs) in addition to the other operator, but no dice. Is this possible at all?

Upvotes: 1

Views: 178

Answers (3)

Null Set
Null Set

Reputation: 5414

map's [] operator only takes the templated class as its parameter. What you want instead is some way of generating a specific instance of your class that has the values you want. In this example, add a constructor that lets you specify the value x should have.

class SomeClass{
   public:
      int x;
      SomeClass(){
         x = rand();
      }
      SomeClass(int a) : x(a){
      }

      bool operator<(const SomeClass& rhs) const{
         return x < rhs.x;
      }

};

And then use

yeah[SomeClass(3)] = "huh";

Or you can just use

yeah[3] = "huh";

which does the same thing, calling SomeClass's constructor implicitly.

Upvotes: 3

sergico
sergico

Reputation: 2621

You can't use yeah[3] as this will require the map to store keys of both SomeClass and int type; Also, consider that each time you add a new element to the map, the "indexed" position of a certain element can change, as the elements are always mainteined ordered by the key element. If you need to look at a certain point in time for the element no j, you can use probably use an iterator on the map.

Upvotes: 0

Hertzel Guinness
Hertzel Guinness

Reputation: 5950

Add a constructor:

SomeClass(int y){
    x = y;
}

Upvotes: 4

Related Questions