如何在c++中,基于对象的某个域,获得对象向量中的最小或最大元素

How to get min or max element in a vector of objects in c++, based on some field of the object?

本文关键字:对象 元素 向量 c++ 于对象      更新时间:2023-10-16

(这是一个相关的问题,但与我的案例存在差异,这让我怀疑我对它的理解)。

我有这个班:

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++的内置函数比我的版本更有效。

尝试以下

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_elementstd::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(), MySuperVector.end(),
                                   MyOwnClass::ByScore() ); 
auto max_index = std::max_element( MySuperVector.begin(), MySuperVector.end(),
                                   MyOwnClass::ByIndex() ); 

您的元素是不同类型的,这并不重要,您可以随时比较您感兴趣的字段:

std::vector<MyOwnClass> MySuperVector(20);
// A pred function to adjust according to your score
bool comparator(const MyOwnClass& s1, const MyOwnClass& s2) {
    return s1.score < s2.score;
}
int main() {
    MySuperVector[0].score = 23; // This will be returned
    MySuperVector[1].score = 2;
    MySuperVector[5].score = -22;
    auto element = std::max_element(MySuperVector.begin(), 
                                    MySuperVector.end(), comparator);
    std::cout << element->score; // 23
}

示例

请注意,您甚至不需要minmax_element函数,因为您只是在请求最大的元素(max_element更适合)。

如果找到最大价值的运行时效率很重要,您可能需要查看priority_queues(heap适配器)。

class test
{
private:
int num;
public:
test()
{
    num = 0;
}
test(int n)
{
    num = n;
}
void get(test ob1,test ob2)
{
    if (ob1.num > ob2.num)
    {
        cout << "Max Object nu is:" << ob1.num << endl;
    }
    else
    {
        cout << "Max Object number is:" << ob2.num << endl;
    }
}
};
void main()
{
test a(6);
test b(4);
test c;
c.get(a,b);
system("pause");
}