如何用多数据对矢量进行排序?

goG*_*Gud 2 c++ sorting algorithm vector

我有这样一个矢量:

struct StatFaces
{
    std::string faceName_1;
    std::string faceName_2;
    float percentagePerson ;
};

std::vector<StatFaces> listFaces_;
Run Code Online (Sandbox Code Playgroud)

我想对那个矢量进行排序 但是我想用组对它进行排序.例如..

I have faceName_1 = john , faceName_2 = kate , percentagePerson = %90
       faceName_1 = john , faceName_2 = nastia , percentagePerson = %95
       faceName_1 = bill , faceName_2 = jamie , percentagePerson = %91 
       faceName_1 = bill , faceName_2 = anna , percentagePerson = %72

output should be ; 

faceName_1 = bill , faceName_2 = jamie, percentagePerson = %91
faceName_1 = bill , faceName_2 = anna , percentagePerson = %72
faceName_1 = john , faceName_2 = nastia , percentagePerson = %95
faceName_1 = john , faceName_2 = kate , percentagePerson = %90
Run Code Online (Sandbox Code Playgroud)

排序算法必须将firstName_1分组,然后根据percentagePerson进行排序

Ps:我不擅长c ++

jua*_*nza 7

您可以将自定义比较功能传递给std::sort.这可以通过std::tie以下方式实现:

#include <tuple> // for std::tie

bool cmp(const StatFaces& lhs, const StatFaces& rhs)
{
  return std::tie(lhs.face_name1, lhs.percentagePerson, lhs.faceName_2) <
         std::tie(rhs.face_name1, rhs.percentagePerson, rhs.faceName_2);
}
Run Code Online (Sandbox Code Playgroud)

然后

#include <algorithm> // for std::sort

std::sort(listFaces_.begin(), listFaces_.end(), cmp);
Run Code Online (Sandbox Code Playgroud)

std::tie返回参数的左值引用元组,并且有一个字典小于比较bool operator<,比较其中两个元组.结果是您在两个StatFaces实例之间执行了一个小于词典的比较.这在内部std::sort用于对元素进行排序.

注意:std::tie在C++ 11实现中可用.如果您没有C++ 11标准库实现,则可以使用std::tr1::tiefrom header <tr1/tuple>boost::tie.您也可以cmp手动实现比较功能.这是一个很好的练习,但它既乏味又容易出错.