欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++ 關(guān)于STL中sort()對struct排序的方法

 更新時間:2013年04月25日 12:05:23   作者:  
本篇文章介紹了,關(guān)于STL中sort()對struct排序的方法。需要的朋友參考下

  前言

  一直沒有系統(tǒng)去看過c++,因為懂得一些c的基本語法,在實際編程中用到c++,只能用到哪些看哪些,發(fā)現(xiàn)這樣雖然能夠完成大部分工作,但是有時候效率實在太低,比如說這節(jié)要講的Std::sort()函數(shù)的使用,調(diào)了半天才調(diào)通。開通c/c++序列博客是記錄在使用c++中一些難題,避免以后重犯錯,當然以后會盡量擠出時間來較系統(tǒng)學(xué)習下c++。

  開發(fā)環(huán)境:QtCreator2.5.1+OpenCV2.4.3

  實驗基礎(chǔ)

  首先來看看std中的快速排序算法sort的使用方法:

  template <class RandomAccessIterator, class Compare> void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );

  這是一個帶模板的函數(shù),參數(shù)1和2表示需要排序的元素在隨機迭代器的起始位置和結(jié)束位置,其迭代器指向的數(shù)據(jù)類型可以自己定義,常見的數(shù)據(jù)類型包括結(jié)構(gòu)體,vector,類等都可以被使用。參數(shù)comp是用來決定所采用的排序是升序還是逆序的,默認情況下是升序排列。但是這種默認情況的優(yōu)勢是處理迭代器指向的元素為普通的數(shù)據(jù)類型,比如說整型,字符型等。如果指向的數(shù)據(jù)類型為類或者結(jié)構(gòu)體,然后使用該類或者結(jié)構(gòu)體中的某個元素進行排序,這時候需要自己定義排序的重載符號”<”。比如說在本次實驗中該重載符號的定義為:

復(fù)制代碼 代碼如下:

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

  如果將comp定義為一個函數(shù)(網(wǎng)上好像很多都是用這種類似的函數(shù)),比如說該函數(shù)如下:
復(fù)制代碼 代碼如下:

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

  則會報錯如下錯誤:

  

  std::sort因為函數(shù)參數(shù)不明確,所以無法推導(dǎo)出模板參數(shù)等.

 

  實驗結(jié)果

  本次實驗是基于這樣一個問題的:有一些坐標點集合(2d的坐標點,坐標點之間沒有重復(fù)),每個坐標點對應(yīng)一個數(shù),現(xiàn)在需要對這些數(shù)排序從而達到對這些坐標點排序。有嘗試過把點的坐標和它對應(yīng)的值放在map中,然后對map中的元素用std::sort()進行排序,但是由于開始沒有發(fā)現(xiàn)那個重載符號的使用,所以沒有調(diào)試成功?,F(xiàn)在直接不用map了,而是用vector,vector里面放的是帶有坐標點和其對應(yīng)值的struct。

  本次實驗是在vector中存入3個結(jié)構(gòu)體對象,每個結(jié)構(gòu)體中放入一個二維點和它對應(yīng)的值,然后采用sort()對齊排序,排序結(jié)果如下:

  

  實驗代碼及注釋

  main.cpp:

復(fù)制代碼 代碼如下:

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

typedef struct
{
    cv::Point point;
    long point_value;
} PAIR;

/*按照降序排列*/
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 << "排序的結(jié)果為:" << endl;
    for(vector<PAIR>::iterator it = vec.begin(); it != vec.end(); ++it) {
        cout << it->point << endl;
    }

    return ;
}

  實驗總結(jié)

  std::sort()函數(shù)的功能很強大,且可以對類,結(jié)構(gòu)體等元素進行排序。

相關(guān)文章

最新評論