基于元组值排序矢量

hem*_*ngh 2 c++ stl

我有以下数据结构,

typedef vector< tuple<int,int,int> > vector_tuple;
Run Code Online (Sandbox Code Playgroud)

在矢量我存储 tuple<value,count,position>

我想根据计数对矢量进行排序,如果计数相同则基于位置对矢量进行排序.

structure ordering
{
  bool ordering()(....)
  {
    return /// ?
  }

};
int main()
{ 
    std::vector<int> v1{1,1,1,6,6,5,4,4,5,5,5};
    std::vector<int> v2(v1);
    vector_tuple vt;
    std::tuple<int,int,int> t1;
    std::vector<int>::iterator iter;
    int sizev=v1.size();
    for(int i=0; i < sizev ; i++)
    {
         auto countnu = count(begin(v2),end(v2),v1[i]);  
         if(countnu > 0)
         {
           v2.erase(std::remove(begin(v2),end(v2),v1[i]),end(v2));
           auto t = std::make_tuple(v1[i], countnu, i);
           vt.push_back(t);
         }
     }
     sort(begin(vt),end(vt),ordering(get<1>vt); // I need to sort based on count and if count is same, sort based on position.


     for (int i=0; i < vt.size(); i++)
     {

        cout << get<0>(vt[i]) << " " ;
        cout << get<1>(vt[i]) << " " ;
        cout << get<2>(vt[i]) << " \n" ;
     }

}
Run Code Online (Sandbox Code Playgroud)

Jar*_*d42 6

您的比较方法应如下所示:

auto ordering = [](const std::tuple<int, int, int>& lhs,
                   const std::tuple<int, int, int>& rhs) {
    return std::tie(std::get<1>(lhs), std::get<2>(lhs))
         < std::tie(std::get<1>(rhs), std::get<2>(rhs));
};

std::sort(std::begin(vt), std::end(vt), ordering);
Run Code Online (Sandbox Code Playgroud)