Only one element in the container can have the key property similar to how rdbms will not allow you to declare
more than one primary key on a table.
Example follows using a vector ( please consider using any other container ( std or boost ) that can accomplish the task
elegantly.
struct Element
{
std::wstring val_;
bool key_;
};
std::vector<Element> v;
Element e1;
e1.val_ = L"Jupiter";
e1.key_ = false;
v.push_back(e1);
Element e2;
e2.val_ = L"Mars";
e2.key_ = true;
v.push_back(e2);
Element e3;
e3.val_ = L"Venus";
e3.key_ = false;
v.push_back(e3);
Element e4;
e4.val_ = L"Venus";
e4.key_ = false;
v.push_back(e4);
Key requirement is that if for example an attempt is made to make e3.key_ = true an exception should be thrown because
e2 (“Mars”) already plays that role
Note that duplicates are allowed in this container.
If you only want to allow one of them to be a key, I would store the indication of the key separately from the individual items:
If you want to, it should be fairly easy to write a little front-end code that acts like an array of bool that will return
truefor an index equal to the value you’ve give forkey, andfalsefor any other value.