i have such a vector:
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
Sort algorithm must group firstName_1 and then sort according to percentagePerson
Ps: I am not good at c++
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);
}
then
#include <algorithm> // for std::sort
std::sort(listFaces_.begin(), listFaces_.end(), cmp);
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.
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.