简体   繁体   English

按向量内的值排序向量 c++

[英]order vector by value inside vector c++

std::vector<vector<float>> tmp = {{1,10,5,4},{2,5,5,1},{3,2,4,3},{4,9,7,8}};

I want to order this vector by the 4th(last) value in vector value.我想通过向量值中的第四个(最后一个)值来排序这个向量。 So the outcome will be like:所以结果会是这样的:

{{2,5,5,1},{3,2,4,3},{1,10,5,4},{4,9,7,8}};

Use std::sort with a suitable lambda for the comparator:std::sort与合适的lambda 一起用于比较器:

std::sort(begin(tmp), end(tmp), [](auto const& inner1, auto const& inner2)
{
    // Note: No checking if the sizes are zero, should really be done
    return inner1.back() < inner2.back();
});

That should do it:那应该这样做:

#include <algorithm>
#include <vector>

int main() {
  std::vector<std::vector<float>> tmp = {
      {1, 10, 5, 4}, {2, 5, 5, 1}, {3, 2, 4, 3}, {4, 9, 7, 8}};

      std::sort(tmp.begin(),tmp.end(), [](auto a, auto b){return a[3]<b[3];} );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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