C++ 数据结构的排序算法

C++ Sort Algorithm for data structures

本文关键字:算法 排序 数据结构 C++      更新时间:2023-10-16

我想使用 stl 排序算法对一些数字进行排序,但我也想记住它们的初始位置。我有一个这样的数据结构:

struct Numbers {
     int position;
     int value;
};

我创建了一个这样的数字向量:

vector<Numbers> a;

如何使用 stl 排序算法,以便根据值对数据结构进行排序?

您也可以

使用函子:

struct comp {
bool operator()(const Numbers &lhs, const Numbers& rhs) const{
  lhs.value < rhs.value;
}
};
std::sort(a.begin(),a.end(), comp());

在 C++11 中,您可以使用 lambda 函数:

std::sort( a.begin() , a.end() , 
          [](const Numbers& lhs , const Numbers& rhs) 
           { return lhs.value < rhs.value; } 
          );
您需要

重载"<"运算符,如下所示:

bool Numbers::operator<(Numbers temp)
{
    return value < temp.value;
}

使用std::sort并提供自定义比较器(模板参数Compare

#include <algorithm>
#include <vector>
//...
std::vector<Numbers> a;
//fill the vector a and set Numbers::position of each element accordingly...
struct {
    bool operator()(const Numbers& a,const Numbers& b)const
    {   
        return a.value < b.value;
    }   
} my_comparator;
std::sort(a.begin(),a.end(),my_comparator);
//...