Custom Sorting a vector of tuples

前端 未结 4 414
自闭症患者
自闭症患者 2021-02-04 04:22

I have a vector of tuples like

vector> v;

I believe that when the default comparison kicks in for tuple types, i

4条回答
  •  别那么骄傲
    2021-02-04 05:04

    So here is the simplest way I learned how to do it (and I think it is even more straightforward than the main answer). This will work on any type in the tuple that can be compared with <.

    Here is the sort function TupleLess, which takes advantage of some C style syntax:

     #include 
     #include 
     #include       
    
     template struct TupleLess
     {
        template
        bool operator() (const Tuple& left, const Tuple& right) const
        {
            return std::get(left) < std::get(right);
        }
    };
    
    int main(){
        //Define a Person tuple:    
        using Person = std::tuple;
    
        //Create some Person tuples and add to a vector
        Person person1 = std::make_tuple("John", "Smith", "323 Fake Street");
        Person person2 = std::make_tuple("Sheila", "Henrod", "784 Unreal Avenue");
        Person person3 = std::make_tuple("Mitch", "LumpyLumps", "463 Falsified Lane");
    
        std::vector vPerson = std::vector();
        vPerson.push_back(person1);
        vPerson.push_back(person2);
        vPerson.push_back(person3);
    
        //Sort by index at position 2
        std::sort(vPerson.begin(), vPerson.end(), TupleLess<2>());
    }
    

提交回复
热议问题