You can use boost :: multi_index using the ordered_unique
and sequence
indexes, as in this example.
#include <iostream> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/member.hpp> // Element type to store in container struct Element { std::string key; int value; Element(const std::string& key, int value) : key(key), value(value) {} }; namespace bmi = boost::multi_index; // Boost multi_index container typedef bmi::multi_index_container< Element, bmi::indexed_by< bmi::ordered_unique< bmi::member<Element,std::string,&Element::key> >, bmi::sequenced<> > > MyContainer; typedef MyContainer::nth_index<1>::type BySequence; // Helper function that returns a sequence view of the container. BySequence& bySequence(MyContainer& container) {return container.get<1>();} int main() { MyContainer container; // Access container by sequence. Push back elements. BySequence& sequence = bySequence(container); sequence.push_back(Element("one", 1)); sequence.push_back(Element("two", 2)); sequence.push_back(Element("three", 3)); // Access container by key. Find an element. // By default the container is accessed as nth_index<0> MyContainer::const_iterator it = container.find("two"); if (it != container.end()) std::cout << it->value << "\n"; // Access container by sequence. Pop elements in a FIFO manner, while (!sequence.empty()) { std::cout << sequence.front().value << "\n"; sequence.pop_front(); } }
source share