c++ - how to sort vector with multi data? -
i have such vector:
struct statfaces { std::string facename_1; std::string facename_2; float percentageperson ; }; std::vector<statfaces> listfaces_; and want sort vector. want sort group. 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 ; 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 , sort according percentageperson
ps: not @ c++
you can pass custom comparison function std::sort. trivially implementable using std::tie:
#include <tuple> // 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> // std::sort std::sort(listfaces_.begin(), listfaces_.end(), cmp); std::tie returns tuple of lvalue reference arguments, , there lexicographical less-than comparison bool operator< compares 2 of these tuples. effect perform less-than lexicographical comparison between 2 statfaces instances. used internally std::sort sort elements.
note: std::tie available in c++11 implementations. if don't have c++11 standard library implementation, can use std::tr1::tie header <tr1/tuple> or boost::tie. can implement comparison function cmp hand. exercise, both tedious , error prone.
Comments
Post a Comment