菜鸟笔记
提升您的技术认知

C++中的结构体vector排序详解

C++中的结构体vector排序详解

使用sort函数对一个vector很常用,前提是通文件中必须包含#include ,但是针对结构体vector排序则需要进行一定的改动。具体事例如下所示:

// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector

bool myfunction (int i,int j) {
   return (i<j); }

struct myclass {
  
  bool operator() (int i,int j) {
   return (i<j);}
} myobject;

int main () {
  
  int myints[] = {
  32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

  // using default comparison (operator <):
  std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33

  // using function as comp
  std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)

  // using object as comp
  std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

但是当vector中的变量是结构体,并且需要按照结构体的某一个元素进行排序时,则需要进行一定的修改:

#include "privateHeader.h"
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using std::string;
using std::vector;
using std::cout;
using std::endl;
using namespace std;

typedef struct
{
  
    float score;
    string file_name;
    string all_file_name;

}TFileProp;

bool GreaterSort(TFileProp a, TFileProp b)
{
  
    return (a.score > b.score);
}
bool LessSort(TFileProp a, TFileProp b)
{
  
    return (a.score < b.score);
}
vector<TFileProp> VecFileProp;

VecFileProp.push_back(tFileProp);    //对vector进行push操作

std::sort(VecFileProp.begin(), VecFileProp.end(), GreaterSort);    //进行降序排序
std::sort(VecFileProp.begin(), VecFileProp.end(), LessSort);    //进行升序排序

还有一点,利用Iang传递参一个数据时,由于命令行接收的参数是以char** argv存储的,因此需要先进行强制类型转换,经过一个string作为中间的转换变量,最终转成int型,另外,我之前认为由于是char型的原因,应该主能传递0-255的参数,但是仔细想一下是不对的,因为无论是多大的数,都是以一个字符串传递进去的,然后string类型再进行强转的时候就转陈了int型,因此并不存在256的大小限制。

int main(int argc, char** argv)
{
  
    // 统计时间
    //timeStatistics();

    // 所有结果放到一个文件夹显示

    int num_save;
    if (argc == 2)
    {
  
        std::string thres = argv[1];
        num_save = atof(thres.c_str());
        //std::cout << "(int)argv[1] is " << argv[1];
        //std::cout << "num_save is " << num_save;
    }
    else
    {
  
        num_save = 100;
    }
    showAllResult(num_save);


    return 1;
}