Использование 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
}
У меня нет каких-либо тестов производительности, но это, безусловно, лучше выражает ваши намерения, и это обычно указывает на улучшение производительности в любом случае.