1. 程式人生 > >sort對結構體進行排序

sort對結構體進行排序

std::sort()函式的功能很強大,且可以對類,結構體等元素進行排序。
首先來看看std中的快速排序演算法sort的使用方法:
  template <class RandomAccessIterator, class Compare> void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
  這是一個帶模板的函式,引數1和2表示需要排序的元素在隨機迭代器的起始位置和結束位置,其迭代器指向的資料型別可以自己定義,常見的資料型別包括結構體,vector,類等都可以被使用。引數comp是用來決定所採用的排序是升序還是逆序的,預設情況下是升序排列。但是這種預設情況的優勢是處理迭代器指向的元素為普通的資料型別,比如說整型,字元型等。如果指向的資料型別為類或者結構體,然後使用該類或者結構體中的某個元素進行排序,這時候需要自己定義排序的過載符號”<”。比如說在本次實驗中該過載符號的定義為:

/*按照降序排列*/
bool compare(const PAIR &x, const PAIR &y)
{
return x.point_value > y.point_value;
}

  如果將comp定義為一個函式(網上好像很多都是用這種類似的函式),比如說該函式如下:
/*按照降序排列*/
bool operator<(const PAIR &x, const PAIR &y)
{
return x.point_value > y.point_value;
}

  則會報錯如下錯誤:

  std::sort因為函式引數不明確,所以無法推匯出模板引數等.
  實驗結果

  本次實驗是基於這樣一個問題的:有一些座標點集合(2d的座標點,座標點之間沒有重複),每個座標點對應一個數,現在需要對這些數排序從而達到對這些座標點排序。有嘗試過把點的座標和它對應的值放在map中,然後對map中的元素用std::sort()進行排序,但是由於開始沒有發現那個過載符號的使用,所以沒有除錯成功。現在直接不用map了,而是用vector,vector裡面放的是帶有座標點和其對應值的struct。
  本次實驗是在vector中存入3個結構體物件,每個結構體中放入一個二維點和它對應的值,然後採用sort()對齊排序,排序結果如下:
/*按照降序排列*/
bool operator<(const PAIR &x, const PAIR &y)

{
return x.point_value > y.point_value;
}

///*按照降序排列*/
//bool compare(const PAIR &x, const PAIR &y)
//{
// return x.point_value > y.point_value;
//}

void main()
{
PAIR pair1, pair2, pair3;
std::vector<PAIR> vec;
pair1.point = Point(10, 20);
pair1.point_value = 100;
pair2.point = Point(70, 30);
pair2.point_value = 99;
pair3.point = Point(44, 76);
pair3.point_value = 101;

vec.push_back(pair1);
vec.push_back(pair2);
vec.push_back(pair3);
// std::sort(vec.begin(), vec.end(), compare);
std::sort(vec.begin(), vec.end());
cout << "排序的結果為:" << endl;
for(vector<PAIR>::iterator it = vec.begin(); it != vec.end(); ++it) {
cout << it->point << endl;