I have a structure containing 3 fields, two int
s (let's call them A and B) and a bool
(C).
I want to create a sort of array of that struct and be able to access it through any of the keys (A or B), getting the hole object (with A, B and C) in return. I won't need to do something like "getting all the object for which the bool is true", if that makes any difference.
Obviously, both key are unique and the bool can't be, but I thought I'd mention it for the sake of clarity.
If there was no A or B, it would be a simple std::map<int, bool>
.
The only solution I currently see is to make a wrapper containing 2 set
s and a vector
.
Is there any way to make my life easier?
NB: It will contain at most a hundred tuples, so performance should not be an issue. Linear access is acceptable.
To make it even clearer, here is what I'd like to be able to do:
foobar<int, int, bool> array; // or something along those lines
array.add(1, 101, true);
array.add(2, 102, false);
array.getA(1); // returns first object
array.getA(2); // returns second object
array.getB(102); // returns second object again
I believe what you're looking for is boost::multi_index. It'll allow you to declare a container with multiple indices.
struct MultiIDStruct
{
size_t idA;
size_t idB;
std::string name;
};
namespace mul = boost::multi_index;
boost::multi_index_container< MultiIDStruct,
mul::indexed_by<
mul::ordered_unique< mul::member< MultiIDStruct, size_t, &MultiIDStruct::idA > >,
mul::ordered_unique< mul::member< MultiIDStruct, size_t, &MultiIDStruct::idB > >
> > data;
(Used namespace "shortcut" as per Rapptz suggestion)
For example here you have a multi_index
container of MultiIDStruct
for which there are two unique orderings, one on idA
(which is a member of MultiIDStruct
) and a second on idB
(which is also a member).
The template parameters seem like a handful at first but they're not so bad once you understand how they work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With