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;
}

      

+1


a source to share


4 answers


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;

      

+5


a source


Create map<string,int> m;

where values ​​are indices for vector<City>

e.g. m["NY"] == 0

and m["LA"] == 1

.



+1


a source


Use two collections:

  • A list to store the actual objects in the order you are interested in.
  • Map for mapping names to objects.
0


a source


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.

0


a source







All Articles