【发布时间】:2023-01-26 01:26:06
【问题描述】:
我定义了一个类,并且有一个包含这些类实例的向量。我想按类的一个属性对向量进行排序。我覆盖了 operator< 以便它知道如何对其进行排序。我的理解是 operator< 是默认的排序方法。好像我错过了一些简单的东西。下面是我正在尝试做的精简版。有任何想法吗?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
class C {
std::string name;
public:
C() {};
C(std::string s) {
name = s;
}
const std::string getName() {
return name;
}
bool operator<(const C& x) const {
return (name > x.name);
}
};
int main() {
std::vector<C*> v;
C* c;
c = new C("Tom");
v.push_back(c);
c = new C("Jane");
v.push_back(c);
c = new C("Dick");
v.push_back(c);
c = new C("Harry");
v.push_back(c);
std::sort(v.begin(), v.end());
for (int i = 0; i < v.size(); i++) {
std::cout << v[i]->getName() << std::endl;
}
}
每次我运行它时,它们都会以随机顺序返回。我怀疑我的 operator< 没有被使用,它们只是按照它们在内存中的地址进行排序。
【问题讨论】: