c++ - STL 或 BOOST map 中是否有类似具有查找和弹出操作的容器?

标签 c++ boost stl map std

我希望我的 map 是可搜索的,并且我希望能够从其中踢出很久以前插入其中的元素(使用类似 map.remove(map.get_iterator_to_oldest_inserted_element()) ) 像 queqe 和 map 的混合。STL 或 Boost 中有这样的容器吗?

最佳答案

您可以使用 boost::multi_index使用 ordered_uniquesequence 索引,如本例所示。

#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();
    }
}

关于c++ - STL 或 BOOST map 中是否有类似具有查找和弹出操作的容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7704526/

相关文章:

c++ - 参数包函数参数可以默认吗?

c++ - 使用 C++ Boost 库有哪些优势?

c++ - 使用 g++ 4.8 (Mac Ports) 在 Mac OS X 上编译 boost::program_options

hash - 为什么 hastable 的 rehash 复杂度在最坏的情况下可能是二次方的

c++ - 从 C++ 调用较低级别的系统命令

c++ - 模板构造函数出现预期的不合格 ID 错误

c++ - 构造函数中不清楚的段错误

c++ - 在一个表达式中 boost to_upper 字符指针

c++ - std::size_t 或 std::vector<Foo>::size_type?

c++ - 读取 vector<char> 作为流