调用c++标准库的algorithm中的sort对vector中的自定义类型进行排序
调用c++标准库的algorithm中的sort对vector中的自定义类型进行排序
#include <iostream>
#include <vector>
#include <set>
#include <tuple>
#include <algorithm>
#include <random>
#include <chrono>
using namespace std;
class ValueIJK {
public:
ValueIJK(float value, int i, int j, int k) {
this->_value = value;
this->_i = i;
this->_j = j;
this->_k = k;
}
float getValue() { return _value; };
int getI() { return _i; };
int getJ() { return _j; };
int getK() { return _k; };
private:
float _value;
int _i;
int _j;
int _k;
};
/// <summary>
/// if a is less than b
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
bool cmpDescend(ValueIJK a, ValueIJK b)
{
return a.getValue() < b.getValue(); // 降序
}
/// <summary>
/// if a is bigger than b
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
bool cmpIncrease(ValueIJK a, ValueIJK b)
{
return a.getValue() > b.getValue(); // 升序
}
int main(int argc, char* argv[]) {
default_random_engine e;
uniform_real_distribution<float> u(0.0, 1.0);
vector<ValueIJK> tupleVec;
int ni = 10;
int nj = 10;
int nk = 10;
for (int k = 0; k < nk; k++) {
for (int j = 0; j < nj; j++) {
for (int i = 0; i < ni; i++) {
tupleVec.push_back(ValueIJK(u(e), i, j, k));
}
}
}
chrono::steady_clock::time_point time_start = chrono::steady_clock::now();
sort(tupleVec.begin(), tupleVec.end(), cmpIncrease);
chrono::steady_clock::time_point time_end = chrono::steady_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(time_end - time_start);
cout << "sort time use:" << time_used.count() << "s" << endl;
for (auto item : tupleVec) {
cout << item.getValue() << " " << item.getI() << " " << item.getJ() << " " << item.getK() << endl;
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具