C++ 如何获得具有多个索引的对象列表?
我想支持带有索引的对象列表。例如:C++ 如何获得具有多个索引的对象列表?,c++,C++,我想支持带有索引的对象列表。例如: struct customer { string first_name; string last_name; Color favorite_color; }; template <typename T> class indexed_list { // ... } indexed_list<customer> allCustomers; // ...populate the list... list<custo
struct customer
{
string first_name;
string last_name;
Color favorite_color;
};
template <typename T>
class indexed_list
{
// ...
}
indexed_list<customer> allCustomers;
// ...populate the list...
list<customer> customersNamedBob = allCustomers.get_first_name("Bob");
list<customer> customersThatLikeRed = allCustomers.get_color(Colors.Red);
struct客户
{
字符串名;
字符串last_name;
颜色最喜欢的颜色;
};
模板
类索引列表
{
// ...
}
列出所有客户;
//…填充列表。。。
list customersNamedBob=allCustomers.get_first_name(“Bob”);
列出喜欢的客户=所有客户。获取颜色(Colors.Red);
当然,一个选项是使用SqLITE或类似的东西,但是假设我想用简单的C++数据结构来做这件事,我该怎么办呢?或者,什么是免费提供的
我的计划是将数据存储为
列表
,然后有一系列[无序]映射
,将索引绑定到实际值。可以理解的是,对于任何类型的T
来说,使其通用化都有点困难,因此可能会有一些逻辑进入customer\u list
类,该类使用indexed\u list
基类中的helper实用程序,或者类似的东西。想法?在boost::multiindex上获得战利品
如果最终只使用了几个索引组合,则最好根据需要生成它们
std::list<Customer> customersNamedBob;
std::copy_if(std::begin(listOfAllCustomers), std::end(listOfAllCustomers),
std::back_inserter(customersNamedBob),
[](const Customer& c) { return !c.name.compare("Bob"); });
如果速度确实是关键,您可以维护以不同方式排序的多个
std::list
,然后使用std::lower_bound
+std::upper_bound
来回答查询。这与sql数据库的功能没有什么不同 mapfind\u如果
没有问题,那有什么问题呢?但是对于列表
来说,需要访问列表中的每个对象才能返回,因此对于长列表来说,速度会非常慢。如果使用set
等,基本上是在单个元素上建立索引,但在某些情况下需要更多。在某些情况下,您确实希望为所有字段编制索引;拥有一个索引并不一定是一件坏事:)map
(我想你的意思是这样的)确实可以为一个整型字段建立索引,这基本上就是我所建议的,尽管封装在一个接口中。我想这是最好的答案;可悲的是,我现在的雇主不允许使用它,尽管我尽了最大的努力说服他们不这样做,所以我在寻找最有意义的替代品:P
template <class Fn>
list<Customer> query(const list<Customer>& table, Fn fn) {
std::list<Customer> result;
std::copy_if(std::begin(listOfAllCustomers), std::end(listOfAllCustomers),
std::back_inserter(customersNamedBob),
[](const Customer& c) { return fn(c); });
customersNamedBob = query(listofAllCustomers, [](const Customer&c) { ... });