I want my map to be searchable and I want to be capable to kick out from it elements that were inserted into it longest 开发者_运维知识库time ago (with api like map.remove(map.get_iterator_to_oldest_inserted_element())
) like mix of queqe and map.. Is there any such container in STL or Boost?
You can use boost::multi_index using the ordered_unique
and sequence
indices, 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();
}
}
You can set up a boost multi-index container to do this.
However, I have trouble understanding multi-index containers. I think it would be easier to roll my own class that has as members a std::queue
and a std::map
, and manage it myself.
There is nothing like that in boost and stl, but you can make a hybrid one yourself:
map<Key, Value> Map;
deque<Key> Queue;
void insert(const Key &k, const Value &v)
{
Map[k] = v;
Queue.push_back(k);
}
void pop_front()
{
const Key &k = Queue.front();
Map.erase(k);
Queue.pop_front();
}
If you only ever want to find the oldest (or newest -- or more generally the least/greatest by some specified criteria, and be able to remove that element), then a priority_queue
will do the job.
Boost::bimap can be used to create a unidirectionnal map using a list-based relation set.
typedef bimap<set_of<A>, unconstrained_set_of<B>, list_of_relation> custom_map_type;
custom_map_type map;
map.push_back(custom_map_type::value_type(A(), B()));
// delete the front of the list (the first inserted element if only using push_back)
map.pop_front();
// otherwise, set.right behave a lot like a std::map<A,B>, with minor changes.
精彩评论