How to do sorting in classes?

2

The funny thing is that this was an answer! The problem I have is this: I have a Person class, which is initialized with a string, and it splits into a number and another string. After the class is mounted, I get an entire file and split it into several strings, which will create multiple variables (objects). They should be drawn by number, and show everything on the screen. I mounted the program but it shows nothing! My code is:

#include <iostream> //cout - main
#include <string> //string - main ,class and func
#include <algorithm> //reverse, sort, greater - class
#include <vector> //vector - main and func
#include <sstream> //stringstream - main

using namespace std;
class Person
{
    private:
        string name_;
        unsigned num_;
    public:
        Person(string raw)
        {
            this->num_ = stoi(raw);
            reverse(raw.begin(), raw.end()); //Those "reverse" are for getting only the number and the string
            raw = raw.substr(0, raw.find(' '));
            reverse(raw.begin(), raw.end()); //Ends here :P
            this->name_ = raw;
        }
        string name() {return this->name_;}
        unsigned num() {return this->num_;}
};

vector<Person> order_vector(vector<Person>& rawPerson)
{
        //Ok, lets check which one is the first
    vector<Person> ret;
    vector<unsigned> values;
    for(unsigned i = 0; i < rawPerson.size(); i++) values.push_back(rawPerson[i].num());
    sort(values.begin(), values.end(), greater<unsigned>());
    for(unsigned a = 0; a < rawPerson.size(); a++)
    for(unsigned i = 0; i < rawPerson.size(); i++)
    {
        if(a == rawPerson[i].num()) ret.push_back(rawPerson[i]);
    }
    return ret;
}

int main()
{
    string raw_strings;
    vector<Person> rawPerson;
    vector<Person> ordened_Person;
    stringstream rawstring(string("10 tennent\n9 Eccleston\n12 Capaldi\n11 Smith"));
    while(getline(rawstring, raw_strings)) //get info before '\n'
    {
        if(!raw_strings.empty()) //If it is not an '\n'
        {
            rawPerson.push_back(Person(raw_strings)); // add an object
        }
    }
    ordened_Person = order_vector(rawPerson);
    for(auto& a : ordened_Person) std::cout << a.num() << '\t' << a.name() << std::endl;
}

I believe the error is in returning the ordered vector, which is most likely. What am I doing wrong?

    
asked by anonymous 30.03.2014 / 04:02

1 answer

3

The good way to implement this is to make your class be comparable, implement operator< . So:

bool Person::operator<(const Person& other) {
    return num_ < other.num_;
}

Now you can sort any container of people using std::sort :

std::sort(vecPerson.begin(), vecPerson.end());

Or:

std::sort(vecPerson.begin(), vecPerson.end(),
          [](const Person& p1, const Person& p2){ return p1.num() < p2.num(); });

Reinventing something that the standard already does is rarely a good idea.

    
30.03.2014 / 12:51