c++ - 如何对结构容器的 vector 进行排序?

标签 c++ sorting vector struct

<分区>

我有一个结构:

struct particle {
double x;
double y;
double Th;
double wt;
};

我还有一个 vector vector<particle> vec如何对 vector vec 进行排序根据递增资料员wt我希望我的 vector 按 double wt 递增排序我想到了使用 std::sort但我该如何补偿结构?

最佳答案

其实很简单:

std::sort(vec.begin(), vec.end(), 
    [](const particle& a, const particle& b) -> bool 
    { 
        return a.wt < b.wt;
    } 

这会根据 wt 的值对 vector 进行排序, 递增顺序。

您还有另一个选择:定义 operator<对于 particle ,如下:

bool operator<(const particle& a, const particle& b)
{
    return a.wt < b.wt;
}

然后,当调用 std::sort 时,你可以这样做:

std::sort(vec.begin(), vec.end());

使用上面的代码, std::sort 会调用operator<每对 particles ,现在有重载来比较它们。

如果您注意到,我一开始使用的 lambda 与我上面使用的函数重载相同。这很容易说明 STL 和 C++ 的优美性和灵 active 。

关于c++ - 如何对结构容器的 vector 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48342907/

相关文章:

c++ - 在 C++ 中拆分一个字符串(使用 strtok?),用逗号分隔符分隔并且不使用外部库?

c - 使用 qsort 排序后存储原始索引

python - 根据条件从字典列表中生成唯一的字典对

iphone - 在 iPhone 上绘图

c++ - c++中友元声明的内容错误基础

c++ - 哪个进程拥有给定端口(Linux 内核)?

c++ - 在 QTabWidget 上显示/隐藏子选项卡

Swift:按属性对列表对象进行排序

c++ - glvertexpointer std::vector, struct memory opengl

c++ - std::vector<int> sum ASM 解释