2

In the below C++ snippet,

HOW TO SORT the vector "TwoIntsVec" BASED ON the element "int a" in TwoInts struct. i.e. i need to place the "TwoIntsVec[i] which has the least "TwoIntsVec[i].a" in the 1st place and so on in increasing order of "TwoIntsVec[i].a".

In the below example the vector elemnt struct having 7,3 should be placed 1st as 7 is the least "a" and so on.

struct TwoInts
{
    int a;
    int b;
};

void PushToVector(int a, int b, std::vector<TwoInts>& TwoIntsVec)
{
    TwoInts temp;
    temp.a = a;
    temp.b = b;
    TwoIntsVec.push_back(temp);
}

int main()
{
    std::vector<TwoInts> TwoIntsVec;
    PushToVector(21,3,TwoIntsVec);
    PushToVector(7,3,TwoIntsVec);
    PushToVector(12,3,TwoIntsVec);
    PushToVector(9,3,TwoIntsVec);
    PushToVector(16,3,TwoIntsVec);

    // Below sort would NOT work here, as TwoIntsVec is
    // not a std::vector<int>
    std::sort( TwoIntsVec.begin(),  TwoIntsVec.end()); 

   // HOW TO MAKE THE SORT BASED ON the element "int a" in 
   TwoInts struct



}
codeLover
  • 3,720
  • 10
  • 65
  • 121
  • 1
    Either implement an `operator<` function for your structure, or pass a predicate (for example a [lambda expression](https://en.cppreference.com/w/cpp/language/lambda)) to [`std::sort`](https://en.cppreference.com/w/cpp/algorithm/sort). – Some programmer dude Mar 21 '19 at 13:14

1 Answers1

5

You need to pass an appropriate comparison function to std::sort, as there is no appropriate comparison operator available for TwoInts. See overload #3 here with the description of this comparison parameter:

comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second. [...]

One C++11 option is to pass a lambda:

 std::sort( TwoIntsVec.begin(),  TwoIntsVec.end(),
     [](const TwoInts& lhs, const TwoInts& rhs){ return lhs.a < rhs.a;  });

If you find that this requires too much typing, you can construct a predicate with Boost HOF like this:

#include <boost/hof/proj.hpp>
#include <boost/hof/placeholders.hpp>

using namespace boost::hof;

std::sort(TwoIntsVec.begin(), TwoIntsVec.end(), proj(&TwoInts::a, _ < _));

Or, as a C++20 teaser:

std::ranges::sort(TwoIntsVec, std::less<>{}, &TwoInts::a);

As a side note, I'd recommend you to fill the vector directly via

// Less complicated than doing the same thing in a function:
TwoIntsVec.push_back({21, 3});
TwoIntsVec.push_back({7, 3});

// ...
lubgr
  • 37,368
  • 3
  • 66
  • 117