简体   繁体   中英

Sort std::vector by an element inside?

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM