Given a class with two keys:
class A {
int key1;
int key2;
byte x[]; // large array
}
If multiple objects of class A
are instantiated and I want to sort them by key1
, I can insert them into an std::set
.
But if I want to sort these objects both by key1
and by key2
, how would I do that?
I could create two sets where one set sorts by key1
and the other set sorts by key2
, but that doubles the amount of memory used. How can I avoid this?
Edit 1:
As far as I know, when an object is inserted into a set, the object is copied. So if I create two sets (one sorted by key1
and one sorted by key2
), that means two versions of the object will exist: one in set1
and one in set2
. This means that member x
also exists twice, which unnecessarily doubles the amount of memory used.
Edit 2:
To give a more specific example: given the class Person
.
class Person {
std::string name;
std::string address;
// other fields
}
I want to be able to find people either by their name and by their address. Both keys won't be used at the same time: I want to be able to call find(name)
and find(address)
.
Also, objects of the Person
class won't be added or removed from the datastructure that often, but lookups will happen often. So lookups should ideally be fast.
Edit 3:
Storing pointers to the objects in the set
instead of the objects themselves seems like a good solution. But would it be possible to store pointers in both sets? I.e.
std::set<A*> set_sorted_by_key1;
std::set<A*> set_sorted_by_key2;
A *obj_p = new A();
set_sorted_by_key1.insert(obj_p);
set_sorted_by_key2.insert(obj_p);