【问题标题】:How to sort a vector with given column only on a triplet value? [duplicate]如何仅对三元组值对具有给定列的向量进行排序? [复制]
【发布时间】:2021-01-14 11:15:00
【问题描述】:

我有一个结构体,其中包含三个 int

struct x{
int a,
    b,
    c;
};

我正在使用结构将三元组存储在向量中,因为三元组将代表sourcedestinationweight

vector<x> myVec;

我正在使用myVec.push_back({a, b, c});在其中添加值

到目前为止一切顺利,但我想根据它们的权重对它们进行排序,那就是 c 变量。我不确定如何在我的矢量上使用std::sort

【问题讨论】:

  • 注意,这很容易成为std::tuple
  • 如果您有 struct,请编写自定义比较器 operator&lt;

标签: c++ sorting vector lambda function-object


【解决方案1】:

您可以使用 lambda 表达式作为示例

#include <vector>
#include <iterator>
#include <algorithm>

// ...

std::sort( std::begin( myVec ), std::end( myVec ),
           []( const auto &a, const auto &b )
           {
               return a.c < b.c;
           } ); 

您可以直接在std::sort 的调用中定义 lambda 表达式对象,如上所示,也可以单独定义,如以下演示程序所示

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

struct x{
int a,
    b,
    c;
};

int main() 
{
    std::vector<x> myVec =
    {
        { 2, 2, 2 }, { 1, 1, 1 }, { 3, 3, 3 }
    };
    
    for ( const auto &item : myVec )
    {
        std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
    }
    std::cout << '\n';
    
    auto compare_by_weight = []( const auto &a, const auto &b )
    {
        return a.c < b.c;
    };
    
    std::sort( std::begin( myVec ), std::end( myVec ), compare_by_weight );
    
    for ( const auto &item : myVec )
    {
        std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
    }
    std::cout << '\n';
    
    return 0;
}

程序输出是

2 2 2
1 1 1
3 3 3

1 1 1
2 2 2
3 3 3

另一种方法是定义一个函数对象。例如。

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

struct x{
int a,
    b,
    c;
};

struct compare_by_weight
{
    bool operator ()( const x &a, const x &b ) const
    {
        return a.c < b.c;
    }
};

int main() 
{
    std::vector<x> myVec =
    {
        { 2, 2, 2 }, { 1, 1, 1 }, { 3, 3, 3 }
    };
    
    for ( const auto &item : myVec )
    {
        std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
    }
    std::cout << '\n';
    
    std::sort( std::begin( myVec ), std::end( myVec ), compare_by_weight() );
    
    for ( const auto &item : myVec )
    {
        std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
    }
    std::cout << '\n';
    
    return 0;
}

程序输出是

2 2 2
1 1 1
3 3 3

1 1 1
2 2 2
3 3 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2018-06-03
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 2020-03-28
    相关资源
    最近更新 更多