Have a look at std::sort
. That function allows you to sort a collection using a predicate that you may specify yourself. In the example code below I create a vector
of pair
s. The cmp
function compares two of these pairs by calculating the ratio for each and returning true
if a
's ratio is greater than b
's.
So effectively you need to specify a function (or a function object, or lambda or whatever) that takes two arguments of your collections element-type and compares them. If a
should come before b
, then the function should return true
, and if not then it should return false
. That function is the third argument for std::sort
#include <algorithm>
#include <vector>
bool cmp(const std::pair<int, int>& a, const std::pair<int, int>& b)
{
// you should probably also add some code to prevent dividing by zero...
return (static_cast<double>(a.first)/a.second) > (static_cast<double>(b.first)/b.second);
}
int main()
{
std::vector<std::pair<int, int> > pairs;
std::sort(pairs.begin(), pairs.end(), &cmp);
}