【问题标题】:Order like a list but access by a key?像列表一样订购但通过键访问?
【发布时间】:2009-05-23 15:54:18
【问题描述】:

我使用列表将城市放入旅行中。然后我迭代 显示旅行行程的列表。我想访问 城市名称而不是旅行顺序。所以我 以为我可以使用地图而不是列表,但关键决定了 命令。我仍然想控制序列的顺序 但可以通过键访问条目。

这些功能可以结合起来吗?是否有一些标准的方法来解决 这个?

#include <list>
#include <iostream>
struct City{
   City(std::string a_n, int a_d):name(a_n), duration(a_d){}
   std::string name;
   int duration;
};
int main(){
    std::list<City*> trip;
    trip.push_back(new City("NY", 5));
    trip.push_back(new City("LA", 2));
    for (std::list<City*>::iterator ii=trip.begin(); ii!=trip.end(); ++ii)
        std::cout << (*ii)->name << " for " << (*ii)->duration << " days." <<std::endl;
}

【问题讨论】:

  • Youn 不应该使用任何 HTML 标签来格式化 SO 帖子。要格式化代码,请用鼠标选择所有代码并键入 Ctrl-K。
  • Neil - HTML 标签有什么大不了的?如果它冒犯了您,请随时编辑帖子并修复它。没必要生气

标签: c++ stl containers


【解决方案1】:

您通常需要编写多个列表和地图。常见的方法是从列表中的指针存储指向城市查找地图中城市的指针。或者你可以使用像Boost.MultiIndex 这样的类来做你想做的事,我想说的是更干净。如果您想添加新索引,它的扩展性也更好,并且样板代码也更少。通常也是more space and time efficient

typedef multi_index_container<
  City,
  indexed_by<
    sequenced<>, //gives you a list like interface
    ordered_unique<City, std::string, &City::name> //gives you a lookup by name like map
  >
> city_set;

【讨论】:

    【解决方案2】:

    创建一个map&lt;string,int&gt; m;,其中的值是vector&lt;City&gt; 的索引,例如m["NY"] == 0m["LA"] == 1

    【讨论】:

    • 通过索引访问列表是一项昂贵的操作。将名称映射到迭代器会更明智。
    • 在我的回答中将 list 更改为 vector。感谢您提出这个问题。
    【解决方案3】:

    使用两个集合:

    • 按您感兴趣的顺序存储实际对象的列表。
    • 将名称映射到对象的映射。

    【讨论】:

      【解决方案4】:

      最好的解决方案是使用Boost.MultiIndex,尽管这稍微复杂一些。不幸的是,我现在没有时间提供示例代码;对不起。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-07
        • 1970-01-01
        • 2017-07-30
        • 1970-01-01
        • 2021-03-03
        • 2010-11-20
        • 2013-01-06
        相关资源
        最近更新 更多