gpt4 book ai didi

c++ - 调用顺序引用一些信息

转载 作者:行者123 更新时间:2023-11-28 01:06:59 25 4
gpt4 key购买 nike

现在我有 std::map<std::string, Object> myMap .类 Object具有以下功能:int getPriority()void Work() .现在我浏览 map 并想调用 Work由于对象的优先级。

我写了一个非常疯狂的想法:那个 map 的克隆,但它存储在它的优先级的键中,例如:

myMap["3_key1"] = Object();
myMap["6_key2"] = Object();
myMap["0_key3"] = Object();

它排序并且调用在正确的队列中:0_key3; 3_key1; 6_key2 .

但我认为这很慢。我想替换 std::mapunordered_map来自 boost 因为它快了很多。并且没有按键排序。

那么,有什么想法吗?

最佳答案

使用Boost.MultiIndex :

// your class
#include <iostream>
#include <string>

class foo
{
public:
foo(std::string name, unsigned priority, std::string msg) :
mPriority(priority)
{
mName.swap(name); // primitive std::move :)
mMsg.swap(msg); // (default-construct & swap)
}

const std::string& name() const
{
return mName;
}

unsigned priority() const
{
return mPriority;
}

void work() const
{
std::cout << mMsg << std::endl;
}

private:
std::string mName;

unsigned mPriority;
std::string mMsg;
};

// your container
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>

namespace bmi = boost::multi_index;

typedef boost::multi_index_container<foo,
bmi::indexed_by<
// order by name (std::map)
bmi::ordered_unique<
bmi::const_mem_fun<foo, const std::string&, &foo::name>
>,

// order by priority (std::multi_map)
bmi:: ordered_non_unique<
bmi::const_mem_fun<foo, unsigned ,&foo::priority>
>
>
> foo_set;

// test
#include <boost/foreach.hpp>

int main()
{
foo_set fooSet;
fooSet.insert(foo("a", 4, "this is a, priority 4"));
fooSet.insert(foo("b", 3, "this is b, priority 3"));
fooSet.insert(foo("c", 7, "this is c, priority 7"));
fooSet.insert(foo("d", 1, "this is c, priority 1"));

// view as map from name to value
foo_set::nth_index<0>::type& nameView = fooSet.get<0>();

nameView.find("a")->work(); // find "a", print its message
if (nameView.find("e") == nameView.end())
std::cerr << "e not found" << std::endl;

std::cout << std::endl;

// view as multi_map from priority to value
foo_set::nth_index<1>::type& priorityView = fooSet.get<1>();

BOOST_FOREACH(const foo& f, priorityView)
f.work(); // work, in order of priority
}

我没有对其进行任何性能测试,但它肯定能更好地表达您的意图,而且这通常表明性能有所提高。

关于c++ - 调用顺序引用一些信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5572309/

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