调用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;
}

 

posted @ 2022-08-21 10:12  Oliver2022  阅读(15)  评论(0编辑  收藏  举报