C++ - 如何在结构向量中找到结构体一个成员的最大值?

C++ - How to find the maximum of one member of struct in a vector of structs?

本文关键字:一个 成员 最大值 结构体 结构 向量 C++      更新时间:2023-10-16

我有一个结构,它有一个名为id的成员。

struct st
{
int id;
double d;
};
st s1 = {1, 5.6};
st s2 = {2, 5.7};
st s3 = {3, 4.3};
vector<st> vec;
vec.push_back(s1);
vec.push_back(s2);
vec.push_back(s3);
int max = 0;
for(int i=0; i < vec.size(); i++)
{
if(vec[i].id > max)
max = vec[i].id;
}

如何在不使用 for 循环的情况下在这些结构的向量中找到最大 id?我看到了这个答案,但不明白。 有没有更有效的使用*max_element方法?

您链接的答案是关于在向量中搜索满足给定条件的元素。找到最大值是不同的,因为您必须在知道最大元素之前考虑所有元素。

std::max_element允许您选择比较,因此您可以轻松地仅比较id

auto max = *std::max_element(vec.begin(),
vec.end(),
[](const st& a,const st& b) { return a.id < b.id; });                 

你提到了*max_element,因此我想你知道它返回了一个你可以取消引用的迭代器。但是,请注意,如果容器为空,则上述内容将中断(由于取消引用end迭代器而导致未定义的行为(,更安全的方法是:

auto it = std::max_element(vec.begin(),
vec.end(),
[](const st& a,const st& b) { return a.id < b.id; });                 
if (it == vec.end()) throw "max_element called on emtpy vector";
auto max = *it;

附言

[...]不使用for循环?

不要将算法与"无循环"混淆。上面的链接有一个可能的实现,如果你研究它,你会发现它不是魔法,而只是一个普通的循环。alogrithm的优点是表现力强,出错的可能性较小。