我会选择Boost Multi Index
如果值没有直接公开,您甚至可以根据需要从 Property 定义键提取器和索引。(为了便于打印,我将 Property 设为 struct 和 Object 公开,但只要 Property::get_value() 是公开的,这将起作用)
#include <iostream>
#include <string>
#include <algorithm>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/optional.hpp>
struct by_property_value{};
struct byseq{};
struct by_id{};
struct Property{
int value;
std::string name;
int get_value() const{
return value;
}
};
class Object {
public:
int id;
Property property;
};
Object make_object(const int&id, const int& value, const std::string& name){
Object res;
res.id = id;
Property p;
p.value = value;
p.name = name;
res.property = p;
return res;
}
bool operator<(const Object& lhs, const Object& rhs){
return lhs.id < rhs.id;
}
using namespace boost;
using namespace boost::multi_index;
struct property_value_key_extractor{
typedef int result_type;
result_type operator()(const Object& o) const{
return o.property.get_value();
}
};
typedef multi_index_container<
Object,
indexed_by<
sequenced<tag<byseq> >
, ordered_unique<tag<by_id>,member<Object,int,&Object::id> >
, ordered_non_unique<tag<by_property_value> , property_value_key_extractor >
>
> Objects;
using namespace std;
int main(int argc, char *argv[]) {
Objects objects;
objects.push_back(make_object(1,1000,"a"));
objects.push_back(make_object(2,200,"b"));
objects.push_back(make_object(3,50,"c"));
typedef Objects::index<by_property_value>::type objects_by_property_value;
typedef objects_by_property_value::iterator property_value_iterator;
property_value_iterator it = objects.get<by_property_value>().find(200);
if(it != objects.get<by_property_value>().end()){
cout << it->id << " " << it->property.get_value() << " " << it->property.name << endl;
}
cout << "Print by propety value" << endl;
for(property_value_iterator it = objects.get<by_property_value>().begin(); it != objects.get<by_property_value>().end(); it++ ){
cout << it->id << " " << it->property.get_value() << " " << it->property.name << endl;
}
}
输出:
2 200 b
按财产价值打印
3 50 c
2 200 b
1 1000 a