The most appropriate associative STL container when the key is part of an object [C ++]

I have a class like this:

struct Thing
{
    unsigned index;
    // more data members
};

I use std::map<Thing>to contain my Things. The call code looks something like this:

Thing myThing(/*...*/);
std::map<Thing> things;
things[myThing.index] = myThing;
// ...
Thing &thing3 = things[3];

I was wondering if there is an approach that I could use Thing::indexdirectly, without having to implicitly copy it to pair::first.

I think I would need to provide some kind of comparison operator Thing, but that's OK. std::setmay work, but I need the whole object Thingas a key:

std::set<Thing> things;
Thing &thing3 = *things.find(Thing(3));

Besides refactoring Thingin std::pair, can I do better with STL?

+5
source share
4

,

inline bool operator<(const Thing& a,const Thing& b) {
  return (a.index<b.index);
}

std::set<Thing> things;  // Uses comparison operator above

Thing &thing3 = *things.find(Thing(3));

, . / , ; ?

:

Thing , , , , , , :

inline bool operator<(const shared_ptr<Thing>& a,const shared_ptr<Thing>& b) {
  return (a->index < b->index);
}

std::set<shared_ptr<Thing>> things;  // Uses comparison operator above

shared_ptr<Thing> key3(new Thing(3));   

Thing &thing3 = *things.find(key3);

, "" args.

, ( ): std::pair<trivial_key,shared_ptr<heavyweight_object>> std::pair<trivial_key,heavyweight_object> - , (, find) , / heavyweight_object ( , , ).

+2

, . patametrize getter - , , .

+1

, boost:: flyweight , , .

flyweight , map unordered_map, , , Google. .

+1

How about using the memory address of your object as a key on your card?

std::map< void*, std::shared_ptr<MyObject> > myMap;
myMap.insert( std::pair<void*, std::shared_ptr<MyObject> >(object.get(), object) );

Therefore, you do not need to store the key in your object, which, in my opinion, is bad, because the key has nothing to do with the state of the objects.

0
source

All Articles