gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:00:18 26 4
gpt4 key购买 nike

我希望我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com