如何排序矢量与多数据? [英] how to sort vector with multi data?

查看:99
本文介绍了如何排序矢量与多数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个向量:

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

std::vector<StatFaces> listFaces_;

,我想对该向量进行排序。但是我想和组排序。例如..

and i want to sort that vector. However i want to sort it with group. For example..

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

group firstName_1,然后根据percentagePerson排序

Sort algorithm must group firstName_1 and then sort according to percentagePerson

Ps:我不擅长c ++

Ps: I am not good at c++

推荐答案

您可以将自定义比较函数传递给 std :: sort 。这是可以通过使用 std :: tie

You can pass a custom comparison function to std::sort. This is trivially implementable using 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);
}

然后

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

std::sort(listFaces_.begin(), listFaces_.end(), cmp);

std :: tie 返回一个元组lvalue引用参数,并且存在比较这些元组中的两个的小于比较的比较 bool operator 。效果是,您在两个 StatFaces 实例之间执行小于字典的比较。这由 std :: sort 在内部使用以对元素排序。

std::tie returns a tuple of lvalue reference to the arguments, and there is a lexicographical less-than comparison bool operator< that compares two of these tuples. The effect is that you perform a less-than lexicographical comparison between two StatFaces instances. This is used internally by std::sort to sort the elements.

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

Note: std::tie is available in C++11 implementations. If you don't have a C++11 standard library implementation, you can use std::tr1::tie from header <tr1/tuple> or boost::tie. You can also implement the comparison function cmp by hand. That is a good exercise, but it is both tedious and error prone.

这篇关于如何排序矢量与多数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆