加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何根据对象的某些字段在c中的对象向量中获取min或max元素?

发布时间:2020-12-16 10:10:43 所属栏目:百科 来源:网络整理
导读:( This是一个相关的问题,但与我的情况有所不同,这让我怀疑我对它的理解). 我有这门课: class MyOwnClass{ public: int score; Specialcustomtype val1; double index;private:}; 和MyOwnClass的向量 vectorMyOwnClass MySuperVector(20); 有一些代码将值设
( This是一个相关的问题,但与我的情况有所不同,这让我怀疑我对它的理解).

我有这门课:

class MyOwnClass
{ 
public:
    int score; Specialcustomtype val1; double index;
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> // 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的内置函数比我的版本更有效.

解决方法

请尝试以下方法

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

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

另一种方法是为每个字段定义内部功能对象,可用于查找最大值或最小值.例如

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(),MyOwnClass::ByScore() ); 

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读