Using min_element in conjunction with a class that contains a < operator - C++ STL Algorithm

C++ examples for STL Algorithm:min_element

Description

Using min_element in conjunction with a class that contains a < operator

Demo Code

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

class MyClass//w  ww. ja  va 2  s .c o m
{
private:
    int m_Value;

public:
    MyClass(const int value)
        : m_Value{ value }
    {

    }

    int GetValue() const
    {
        return m_Value;
    }

    bool operator <(const MyClass& other) const
    {
        return m_Value < other.m_Value;
    }
};

int main(int argc, char* argv[])
{
    vector<MyClass> myVector{ 4, 10, 6, 9, 1 };
    auto minimum = min_element(myVector.begin(), myVector.end());

    if (minimum != myVector.end())
    {
        cout << "Minimum value: " << (*minimum).GetValue() << std::endl;
    }

    return 0;
}

Result


Related Tutorials