(这个问题与我的情况有所不同,让我对自己的理解产生了怀疑。)
我有这个类:
class MyOwnClass
{
public:
int score; Specialcustomtype val1; double index;
private:
};
和一个MyOwnClass的向量
vector<MyOwnClass> MySuperVector(20);
我有一些代码,用于为MyOwnClass的字段设置值,我想找出在向量中哪个MyOwnClass的字段分数具有最高值。
在相关问题的答案中:
#include <algorithm> // For std::minmax_element
#include <tuple> // For std::tie
#include <vector> // For std::vector
#include <iterator> // For global begin() and end()
struct Size {
int width, height;
};
std::vector<Size> sizes = { {4, 1}, {2, 3}, {1, 2} };
decltype(sizes)::iterator minEl, maxEl;
std::tie(minEl, maxEl) = std::minmax_element(begin(sizes), end(sizes),
[] (Size const& s1, Size const& s2)
{
return s1.width < s2.width;
});
但在我的情况下,MyOwnClass的字段类型不同,我的尝试使用“max_elements”失败了。
当然,我可以循环遍历向量的n个元素,并使用比较来找到得分最高的对象,这样做确实有效,但我相信c++的内置函数比我的版本更有效率。
MyOwnClass的字段类型不同
是什么意思?” - NaCloperator<()
并仅检查score
呢? - David G