现在我有std::map<std::string, Object> myMap
。课程Object
包含以下内容:int getPriority()
和void Work()
。现在我浏览地图,并且由于对象的优先级而想要调用Work
。
我写了一个非常疯狂的想法:该地图的克隆,但它存储在键中它的优先级,例如:
myMap["3_key1"] = Object();
myMap["6_key2"] = Object();
myMap["0_key3"] = Object();
它排序并调用正确的队列:0_key3; 3_key1; 6_key2
。
但我觉得这很慢。我希望将std::map
替换为unordered_map
来自提升,因为它的速度要快得多。而且没有按键排序。
那么,有什么想法吗?
答案 0 :(得分:1)
我认为最简单的方法是两个容器。您当前的key-&gt;值映射,以及按对象的优先级排序的第二个键堆(可能只使用priority_queue
作为堆实现)。这将有困难,优先权可以在飞行中改变。
答案 1 :(得分:1)
如果使用std :: set或std :: priority_queue而不是std :: map,则可以定义一个仿函数,或者只是实现operator&lt;为您的类,以便std :: set按优先级顺序为对象排序。
#include <iostream>
#include <set>
class Object {
public:
int m_priority;
Object(int p) : m_priority(p) { }
int getPriority() const { return m_priority; }
void Work() const { std::cout << m_priority << std::endl; }
};
bool operator<(const Object & lhs, const Object & rhs)
{
return lhs.getPriority() < rhs.getPriority();
}
int main()
{
std::set<Object> container;
container.insert(Object(1));
container.insert(Object(9));
container.insert(Object(5));
container.insert(Object(8));
container.insert(Object(3));
for (std::set<Object>::iterator I = container.begin();
I != container.end();
++I) {
I->Work();
}
}
答案 2 :(得分:1)
// 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
}
我没有对它进行任何性能测试,但它肯定能更好地表达你的意图,而这通常表明性能有所改善。