lundi 28 janvier 2019

Sorting or printing of set of objects is incorrect

I truly don't know whether my sorting or my printing of a set of obejcts is wrong but when I print the whole set, the result is unsorted AND it contains one duplicate. The object Person has a surname, a familyname and year of birth (all 3 are strings). I first sort by year of birth, then by familyname and then by surname. Per se, there are no identical persons (but even if was the case, it should be eliminated as they get inserted into the set ).

To be more concrete, I create a set of persons like this:

std::set <Person> greatUncles; 

and insert them like this:

greatUncles.insert(Person("bla", "bla", "1900"));

Here's are the essential things from class Person:

class Person {
public:
  ...

  Person(std::string s, std::string f, std::string y)
    :surname(s), familyname(f), yearOfBirth(y)
  {
  }

  ...

  std::string getSurname() const {
    return surname;
  }

  std::string getFamilyname() const {
    return familyname;
  }

  std::string getYearOfBirth() const {
    return yearOfBirth;
  }

private:
  std::string surname;
  std::string familyname;
  std::string yearOfBirth;
};

//to print the set, overload the '<<' operator
std::ostream &operator<<(std::ostream &o, const Person &person) {
  o << person.getSurname() << " "
    << person.getFamilyname() << " "
    << person.getYearOfBirth() << std::endl;
  return o;
}

//to order the set, overload the '<' operator
bool operator< (Person const &p1, Person const &p2) {
  int compareYearOfBirth = p1.getYearOfBirth().compare(p2.getYearOfBirth());

  if (compareYearOfBirth == 0) {
    int compareFamilyname = p1.getFamilyname().compare(p2.getFamilyname());
    if (compareFamilyname == 0) {
      return p1.getSurname().compare(p2.getSurname());
    } else
      return compareFamilyname;
  } else
    return compareYearOfBirth;
}

and here is how I print the set of great-uncles:

void printGreatUncles(std::set <Person> &greatUncles) {
    std::ofstream outputFile;
    outputFile.open("greatuncle.dat");

    if (outputFile.is_open()) {
      for(Person const & person:greatUncles) {
        outputFile << person;
      }
      outputFile.close();
    }
  }

Now the output in a certain case should look like this (sorted by year):

Sebastian Furtweger 1942
Nikolaus Furtweger 1951
Archibald Furtweger 1967

but it looks like this:

Archibald Furtweger 1967
Sebastian Furtweger 1942
Nikolaus Furtweger 1951
Archibald Furtweger 1967

I can't figure it for my life what (things) I'm doing wrong.

Aucun commentaire:

Enregistrer un commentaire