我正在尝试对一个数组进行排序,其中包含按字母顺序填充的字符串值。它已经适用于整数。我认为问题不在于排序,而在于显示。
但是这里是代码:
#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 说:二进制表达式的操作数无效
谢谢你和最好的问候 弗洛
最佳答案
sort
可能没有问题.明显错误的是你没有 ostream& operator<<
对于 Ticket
,所以你不能这样做:
for (int i = 0; i < 10; i++) cout << array[i] << endl;
// ^^^^^^^^^^^^^^^^
所以,
friend
std::ostream& operator<<(std::ostream& o, const Ticket& t)
{
return o << t.ticketnr << " " << t.name;
}
关于c++ - 按字母排序字符串数组并显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17477680/