Steg Verner
Steg Verner

Reputation: 913

Sort according to first vector of pair in C++

I have a data structure of the following form:

vector<pair<vector<unsigned>,vector<unsigned> > a;

Now I want to sort the vector "a" according to first vector of pair. E.g. in the example given below, I want to rank according to the following: (((1,2,4),(89,29)) , ((1,3),(67,90))). As size of a3 is greater than size of a1, therefore ranking is done first according to a3 and then a1.

E.g. If 
     vector<unsigned> a1,a3;
     a1.push_back(1); a1.push_back(3);
     vector<unsigned> a2,a4;
     a2.push_back(67); a2.push_back(90);
     a.push_back(make_pair(a1,a2));
     a3.push_back(1); a3.push_back(2); a3.push_back(4);
     a4.push_back(89); a4.push_back(29);
     a.push_back(make_pair(a3,a4));

I know I can do the sorting using bubble sort. But is there some other way in C++ like STL function to do the same.

Upvotes: 2

Views: 305

Answers (1)

TemplateRex
TemplateRex

Reputation: 70556

Just use std::sort with a function object (a lambda here) that compares the first element of each pair (and which uses the operator< from std::vector)

#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>

using namespace std;

int main()
{
    vector<pair<vector<unsigned>,vector<unsigned> >> a = {{{1,3},{67, 90}}, {{1,2,4},{89,29}}};
    sort(begin(a), end(a), [](auto const& L, auto const& R) {
        return L.first < R.first;
    });

    for (auto const& elem : a) {
        std::cout << "{{";
        for (auto const& u : elem.first)
            std::cout << u << ", ";
        std::cout << "},";
        std::cout << "{";
        for (auto const& u : elem.second)
            std::cout << u << ", ";
        std::cout << "}},";
    }    
}

Live Example using C++14.

You can adapt it to C++98 by writing the range-based for loop using iterators / indices, and by writing a separate function object that you pass to std::sort. Oh, and you would also have to use the awkward push_back initialization instead of the more convenient initalizer-lists from C++11 and beyond.

Upvotes: 2

Related Questions