我正在尝试将文件中的数据存储到对象 vector 中,然后对数据成员进行排序,但出现错误“无法确定重载函数“sort”的实例是预期的”。我试过将 lambdas 与 sort 一起使用,也认为这可能是我创建比较函数的方式(是 a.hour > b.hour 还是我应该使用 a.getHour() 和 b.getHour()?)我实际上想按小时和分钟对 vector 进行排序,但首先只在几个小时内测试它似乎不起作用。这是我目前所拥有的
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
using namespace std;
class time {
int hour;
int minute;
public:
time(int h, int m) {
hour = h;
minute = m;
}
int getHour() { return hour; }
int getMinute() { return minute; }
};
class Times {
vector<time> t;
public:
Times(string fileName) {
//
}
void parse(ifstream& file) {
//
sort.(t.begin(), t.end(), lowerThan);
//sort.(t.begin(), t.end(), [] (time& a, time& b) { return a.hour < b.hour; })
}
void display() {
for (size_t i = 0; i < t.size(); i++) {
cout << t[i].getHour() << ":" << t[i].getMinute() << endl;
}
}
static bool lowerThan(time& a, time& b) { return a.getHour() < b.getHour(); }
};
int main() {
Times times("File.txt");
times.display();
system("pause");
return 0;
}
最佳答案
您的代码中存在多个问题。
你 should not use using namespace std;
以避免名称冲突。
此外,不幸的是你的time
(小写)类与另一个冲突 time
标准标识符。只需使用 Uppercase
命名类的约定。
此外,您可能想要标记您的 Time::getHour()
和 Time::getMinute()
方法为 const
,因为它们不修改 Time
的内部状态对象。
您还有一个打字错误 sort
电话,因为您在 sort
之后有一个点.
而且,在 C++11/14 中,我建议您使用基于范围的 for
循环 而不是显式for
具有整数索引。
考虑到这些方面,我对您的代码进行了一些重构,并且 it now works , 与 lowerThan()
静态方法和 lambda。随意研究它。
#include <algorithm>
#include <iostream>
#include <vector>
class Time {
int hour;
int minute;
public:
Time(int h, int m) : hour(h), minute(m) {
}
int getHour() const { return hour; }
int getMinute() const { return minute; }
};
class Times {
std::vector<Time> t;
static bool lowerThan(const Time& a, const Time& b) {
return a.getHour() < b.getHour();
}
public:
Times() {
// Test data
t.push_back(Time{10, 10});
t.push_back(Time{9, 20});
t.push_back(Time{8, 30});
//std::sort(t.begin(), t.end(), lowerThan);
std::sort(t.begin(), t.end(), [] (const Time& a, const Time& b) {
return a.getHour() < b.getHour();
});
}
void display() {
for (const auto& x : t) {
std::cout << x.getHour() << ":" << x.getMinute() << '\n';
}
}
};
int main() {
Times times;
times.display();
}
另请注意,如果您定义自定义 operator<
对 Time
的实例进行排序的重载类,你可以简单地调用std::sort()
没有任何自定义比较器,以及您对 operator<
的自定义实现is automatically picked up by the compiler :
class Time {
...
friend bool operator<(const Time& a, const Time& b) {
return a.getHour() < b.getHour();
// ... or a more complete comparison, including minutes.
}
};
编辑
正如@DieterLücking 在评论中所建议的那样,您可以使用 std::tie()
对于 operator<
实现(live here on Ideone):
#include <tuple> // for std::tie
class Time {
...
public:
friend bool operator<(const Time& a, const Time& b) {
return std::tie(a.hour, a.minute) < std::tie(b.hour, b.minute);
}
};
关于c++ - 使用 std::sort 对包含两个数据成员的对象 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36018505/