0

I have an array of Person objects that contain a member variable, name. I am trying to order them alphabetically using an overloaded comparison operator that uses string::compare to compare the strings in the objects.

bool Person::operator==(Person p) {
    if (name.compare(p.name) == 0) {
        return true;
    }
    else {
        return false;
    }
}

this works and gives me the correct result but I don't know how I can use this to order the names in the array alphabetically.

I have looked around and seen that documentation on string::compare says

relation between compared string and comparing string

  • 0 They compare equal
  • <0 Either the value of the first character that does not match is lower in > the compared string, or all compared characters match but the compared string > is shorter.
  • ,>0 Either the value of the first character that does not match is greater >in the compared string, or all compared characters match but the compared string is longer.

I can't figure out a way to solve my problem with this information though.

Am I on the right track for what I'm trying to do or is there a better way?

luke_k
  • 15
  • 3
  • 2
    I don't see the *pointers* mentioned in your title in *any* this. nor do I see any calls to a sort routine (such as `std::sort`) that is using your custom comparator (which should be `operator <` if you're going to use `std::sort`). In short, I see no [minimal, *complete*, verifiable example](https://stackoverflow.com/help/mcve). – WhozCraig Jan 30 '17 at 19:55
  • The standard library has you covered with [template< class RandomIt, class Compare > void sort( RandomIt first, RandomIt last, Compare comp );](http://en.cppreference.com/w/cpp/algorithm/sort). – Jesper Juhl Jan 30 '17 at 20:03

1 Answers1

2

Your operator is correctly defined, but it is not the operator you are looking for. You want to define the operator <, then use std::sort.

Rémi Bonnet
  • 793
  • 5
  • 16