tags:

views:

115

answers:

3

I currently have a std::vector which holds std::vector of double. I'd want to sort it by the second element of the double vectore. ex: instead of sorting by MyVec[0] or myvec[1] I wat it to sort myVec[0] and myvec[1] based on myvec[0][1] myvec[1][1]. Basically sort by a contained value, not the objects in it.

so if myvec[0][1] is less than myvec[1][1] then myvec[0] and myvec[1] will swap. Thanks

+5  A: 

Just write the comparator:

bool my_comparator(const std::vector<double>& lhs, const std::vector<double>& rhs)
{
  assert(lhs.size() >= 2 && rhs.size() >= 2);
  return lhs[1] < rhs[1];
}
...
std::sort(big_vector.begin(), big_vector.end(), my_comparator);

It is better to write a functor instead of a function, but the concept is the same.

AraK
Thanks :-).....
Milo
Nathan Ernst
@Nathan Sanity checking is a must in real code, but this isn't supposed to be production code :). Anyway, I changed the code according to your suggestion.
AraK
@AraK, cheers. I'm just afraid of too much copy/paste from answers into real code, so I feel we must be pedantic. You've earned my +1.
Nathan Ernst
+1  A: 

This is something like a vector of strings, except instead of a string of characters, we've got a string of numbers. I think you want this:

[
  [1, 0, 4],
  [4, 9, 9],
  [0, 1, 9],
  [4, 5. 2]
]

... to sort to ...

[
  [0, 1, 9],
  [1, 0, 4],
  [4, 5. 2],
  [4, 9, 9]
]

...right?

To do that, you'll need to write a comparator class or function that takes two vectors of numbers, and returns "true" if the first is less than the second. Like:

bool my_comparator(const std::vector<double> &a, const std::vector<double> &b)
{
    // return true if a < b ... by comparing a[0] with b[0], etc.
}

then pass that to sort():

sort(?, ?, my_comparator);
Thanatos
A: 

I tried solving this with boost::lambda, but the compiler gave me almost 23 kb of error messages :)

#include <boost/lambda/lambda.hpp>

int main()
{
    using namespace boost::lambda;

    std::vector<std::vector<double> > vec;

    std::sort(vec.begin(), vec.end(), _1[1] < _2[1]);
}

Filtering all the noise, I get error: invalid initialization of reference of type 'double&' from expression of type 'const double'. How would I fix this?

FredOverflow