如何获得min或max元素在c ++中的对象的向量中,基于对象的一些字段? [英] How to get min or max element in a vector of objects in c++, based on some field of the object?

查看:119
本文介绍了如何获得min或max元素在c ++中的对象的向量中,基于对象的一些字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相关的问题,但我的情况有所不同,让我怀疑我的理解。)



我有这个类:

  class MyOwnClass 
{
public:
int score;特殊类型val1;双指数;
private:

};

和MyOwnClass的向量

  vector< MyOwnClass> MySuperVector(20); 

有一些代码为MyOwnClass的字段设置值,我想在向量中找到MyOwnClass



answer 从相关问题:

  #include< algorithm> // For std :: minmax_element 
#include< tuple> // For std :: tie
#include< vector> // For std :: vector
#include< iterator> //对于全局begin()和end()

struct Size {
int width,height;
};

std :: vector< Size> size = {{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 ++的内置函数比我的版本更有效。

解决方案

  std :: vector< MyOwnClass> MySuperVector(20); 

//..fill向量

auto max = std :: max_element(MySuperVector.begin(),MySuperVector.end(),
[] const MyOwnClass& a,const MyOwnClass& b)
{
return a.score< b.score;
});

如果您需要同时找到最小和最大元素,那么您可以使用标准算法 std :: minmax_element 。它返回一对迭代器,其中第一个指向第一个最小元素,第二个指向最后一个最大元素。否则,你需要调用 std :: max_element std :: min_element separatly。如果您需要获取第一个最小值和第一个最大值或最后一个最小值和最后一个最大值。



另一种方法是为每个字段定义内部函数对象,用于查找最大或最小。例如

  class MyOwnClass 
{
public:
int score;特殊类型val1;双指数;

struct ByScore
{
bool operator()(const MyOwnClass& a,const MyOwnClass& b)const
{
return a.score <分数;
}
};

struct ByIndex
{
bool operator()(const MyOwnClass& a,const MyOwnClass& b)const
{
return a.index < b.index;
}
};
private:

};

// ...

auto max_score = std :: max_element(MySuperVector.begin(),MySuperVector.end(),
MyOwnClass :: ByScore ));

auto max_index = std :: max_element(MySuperVector.begin(),MySuperVector.end(),
MyOwnClass :: ByIndex());


(This is a related question, but there are difference with my case that makes me doubt my understanding of it).

I have this class:

class MyOwnClass
{ 
public:
    int score; Specialcustomtype val1; double index;
private:

};

and a vector of MyOwnClass

vector<MyOwnClass> MySuperVector(20);

Having some code that set values to the fields of MyOwnClass, I want to find which MyOwnClass in the vector has the field score with the highest value.

In an answer from the related questions :

#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;
    });

But in my case, the fields of MyOwnClass are of different types and my attempts at using "max_elements" have failed.

Of course I could loop among the n elements of the vector and use a comparison to find which object has the highest score, and it works but I am sure that the built-in functions of c++ are more efficient thant my version.

解决方案

Try the following

std::vector<MyOwnClass> MySuperVector(20);

//..filling the vector

auto max = std::max_element( MySuperVector.begin(), MySuperVector.end(),
                             []( const MyOwnClass &a, const MyOwnClass &b )
                             {
                                 return a.score < b.score;
                             } ); 

If you need to find the minimum and maximum element simultaneously then you can use standard algorithm std::minmax_element. It returns a pair of iterators the first of which points to the first minimum element and the second points to the last maximum element. Otherwise you need to call std::max_element and std::min_element separatly. if you need to get the first minimum and the first maximum or the last minimum and the last maximum

The other approach is to define internal functional objects for each field that can be used for finding maximum or minimum. For example

class MyOwnClass
{ 
public:
    int score; Specialcustomtype val1; double index;

    struct ByScore
    {
        bool operator ()( const MyOwnClass &a, const MyOwnClass &b ) const
        { 
            return a.score < b.score;
        }
    };

    struct ByIndex
    {
        bool operator ()( const MyOwnClass &a, const MyOwnClass &b ) const
        { 
            return a.index < b.index;
        }
    };
private:

};

//...

auto max_score = std::max_element( MySuperVector.begin(), MySuperVector.end(),
                                   MyOwnClass::ByScore() ); 

auto max_index = std::max_element( MySuperVector.begin(), MySuperVector.end(),
                                   MyOwnClass::ByIndex() ); 

这篇关于如何获得min或max元素在c ++中的对象的向量中,基于对象的一些字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆