(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
{
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() );
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");
}
That your elements are of different types it doesn't matter, you can always compare the field you're interested in:
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
}
Example
Notice that you don't even need the minmax_element
function since you're just asking for the greatest element (max_element is a better fit).
If the runtime efficiency to find your greatest value matters, you might want to take a look at priority_queues (heap adaptors).