Search code examples
c++c++11stlstl-algorithm

Find minimum value of member in list<MyStruct> using STL


I have list of MyStruct objects.

struct Task {
    std::function<void()> _fn = nullptr;
    std::chrono::system_clock::time_point _execTime;
};

How to find minimum value of _execTime in list using STL algorithm ? I can find with iteration, but is there more elegant way to do this? Something like below:

std::chrono::system_clock::time_point nearestExecTime = std::min(auto t = tasks.begin(), auto p = tasks.end(), [t,p]() {return t.execTime < p.exeTime;});

Solution

  • Use std::min_element.

    std::min_element(tasks.begin(), tasks.end(),
    [](const Task& t, const Task& p) { return t._execTime < p._execTime; });