0

I am trying to sort an array with is filled with string values by alphabet. It already works with integers. I think the problem isn’t about the sorting, it is about displaying it.

But here is the code:

#include <iostream>
#include <algorithm>
using namespace std;

class Ticket {
    int ticketnr;
    string name;
public:
    Ticket() {
        ticketnr = 0;
        name = "NN";
    };
    Ticket(int _tickernr, string _name) {
        ticketnr = _tickernr;
        name = _name;
    }
    friend bool upSort(Ticket a, Ticket b);
};

bool upSort(Ticket a, Ticket b) {
    return (a.name > b.name);
}
int main() {

    Ticket vip(1435, "Beckenbauer");
    Ticket frei;

    Ticket array[10] = {vip, Ticket(2100, "Maier")};
    sort(array, array + 10, upSort);
    for (int i = 0; i < 10; i++) cout << array[i] << endl;

}

Xcode says: invalid operands to binary expression

Thank you and best regards Flo

1
  • You have to provide an overloaded operator << for your class. Commented Jul 4, 2013 at 20:30

1 Answer 1

4

There is probably nothing wrong with the sort. What is clearly wrong is that you don't have an ostream& operator<< for Ticket, so you cannot do this:

for (int i = 0; i < 10; i++) cout << array[i] << endl;
//                           ^^^^^^^^^^^^^^^^

So,

friend
std::ostream& operator<<(std::ostream& o, const Ticket& t)
{
  return o << t.ticketnr << " " << t.name;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.