How to sort and display a list of objects in C ++?

advertisements

I am working on an airline reservation system where a user will be able to select how they want a list to be sorted and displayed. Essentially, I created a list of objects where the object members are the names and codes of a few cities. However, I am not sure how to sort this list by the object members and then display the members of that list. Here is where I create and populate the list.

City Class definition:

#ifndef CITY_H
#define CITY_H
#include <iostream>
#include <list>

using namespace std;

class City
{
protected:
    string name;
    string code;

public:
    City()
    {
        name = "";
        code = "";
    }
    void setName(string);
    void setCode(string);
    void addCities();
    void displayCities(const list<City> &);

    string getName();
    string getCode();

    friend ostream& operator<< (ostream& , City &);

};

    ostream& operator<< (ostream& , City &);
#endif //CITY_H

void City::addCities()
{
    ifstream cities;
    cities.open("cities.dat");

    list<City> cityList;

    string co = "", na = "";

    while (!cities.eof())
    {
        City c;
        cities >> co;
        cities >> na;

        c.setCode(co);
        c.setName(na);

        cityList.push_back(c);
    }
    displayCities(cityList);
}

Here is the text file with the information I am loading into the list:

ATL Atlanta
ORL Orlando
DFW Dallas/Fort_Worth
NYC New York City
HAW Hawaii
CHI Chicago
LAX Los_Angeles

And this was my attempt at displaying the list:

void displayCities(const list<City> &cityRef)
{
    list<City>::iterator it;
    for (it == cityRef.begin(); it != cityRef.end(); ++it)
    {
        std::cout << (*it) << std::endl;
    }
}

ostream& operator <<(ostream& s, City& c)
{
    s << c.name << c.code;
    return s;
}


Instead of addCities you really want to overload operator>> for your City class:

struct City {
    std::string code, name;

    friend std::istream &operator>>(std::istream &is, City &c) {
      return is >> c.code >> c.name;
    }
};

Then you can read the data (which you're currently doing incorrectly, BTW) like this:

std::ifstream cities("cities.dat");
std::vector<City> CityList{std::istream_iterator<City>(cities),
                           std::istream_iterator<City>());

Then sort something like:

std::sort(cities.begin(), cities.end(),
          [](City const &a, City const &b) { return a.code < b.code; });

And you can write out the result something like this:

for (auto const &city : CityList)
    std::cout << city << "\n";

Note that I've made CityList a vector instead of a std::list -- the latter is a mistake much more often than not.