像列表一样排序但通过按键访问?
我使用列表将城市放入旅行中。 然后我迭代 显示旅行行程的列表。 我想访问 按城市名称而不是按行程顺序。 所以我 我以为我可以使用地图而不是列表,但关键决定 命令。 我仍然想控制序列的顺序 但能够通过密钥访问条目。
这些功能可以组合起来吗? 有没有一些标准的方法来解决 这?
#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;
}
I used list to place cities into a trip. Then I iterate over
the list to display the trip itinerary. I would like to access
the cities by the name rather than by the trip order. So, I
thought I could use a map rather than a list but the key determines
the order. I would still like to control the order of the sequence
but be able to access the entries by a key.
Can these features be combined? Is there some standard way to address
this?
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
很多时候,您需要编写多个列表和地图。 常见的方法是从列表中的指针存储指向按城市查找地图中的城市的指针。 或者您可以使用类似 Boost.MultiIndex 做你想做的事情,我想说的是更干净。 如果您想添加新索引,它的扩展性也会更好,并且样板代码也会少得多。 通常空间和时间效率更高
Often times you will need to compose multiple lists and maps. The common way is to store a pointer to the Cities in your by city lookup map from the pointers in your list. Or you can use a class like Boost.MultiIndex to do what you want in what I would say is much cleaner. It also scales much better and there is a lot less boiler plate code if you want to add new indexes. It is also usually more space and time efficient
创建一个
map; m;
,其中值是向量
的索引,例如m["NY"] == 0
和m[ “LA”] == 1
。Create a
map<string,int> m;
, where the values are indexes to avector<City>
, for examplem["NY"] == 0
andm["LA"] == 1
.使用两个集合:
Use two collections:
最好的解决方案是使用 Boost.MultiIndex,尽管这稍微复杂一些。 不幸的是,我现在没有时间提供示例代码; 对不起。
The best solution is to use Boost.MultiIndex, though that's slightly more involved. Unfortunately, I don't have time now to provide sample code; sorry.