Sort vector of vectors

后端 未结 4 1639
离开以前
离开以前 2021-02-13 22:20

I have

    vector> vec 

in my c++ app.

Every vector of integers as an element of \"big\" vector has 4 INT valu

4条回答
  •  伪装坚强ぢ
    2021-02-13 22:26

    Sure it is. std::sort can take a third parameter which is the comparison function to use when sorting. For example, you could use a lambda function:

    std::vector> vec;
    // Fill it
    
    std::sort(vec.begin(), vec.end(),
              [](const std::vector& a, const std::vector& b) {
      return a[2] < b[2];
    });
    

    Alternatively, you can pass anything else callable with signature bool(const std::vector&, const std::vector&), such as a functor or function pointer.


    Response to edit: Simply apply your COST function to a and b:

    std::sort(vec.begin(), vec.end(),
              [](const std::vector& a, const std::vector& b) {
      return COST(a) < COST(b);
    });
    

提交回复
热议问题