Ordering like a list but accessing a key?
I used the list to put cities on the journey. Then I iterate over the list to display the route of the trip. I would like to access the city by name, not by order. So I thought I could use a card, not a list, but the key defines the order. I would still like to control the order of the sequence but be able to access the records using a key.
Can these functions be combined? Is there some standard way of solving 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;
}
a source to share
Often times, you need to make several lists and maps. The usual way is to store a pointer to Cities in the city search 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 boilerplate code if you want to add new indexes. Usually also more free space and time
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;
a source to share
Better solution is to use Boost.MultiIndex , although this is a little more proactive. Unfortunately, I don't have time to provide a sample code; sorry.
a source to share