How to write own code to replace `std::min_element` to find smallest value in vector

305 views Asked by At

I try to find the smallest value in a std::vector container.

I know std::min_element works fine. But I am coding for a stm32 chip, that supports c++11. However, the cross compiler has some issues with <algorithm> header.

I want a clear and effect way to do that.

Any suggestions will be appreciated.

2

There are 2 answers

0
Zereges On

Generic std::min_element implementation might look like this. It returns iterator to minimum and end for empty range and supports custom comparator function.

template
<
    typename ForwardIt,
    typename Cmp = std::less<typename std::iterator_traits<ForwardIt>::value_type>
>
ForwardIt min_element(ForwardIt begin, ForwardIt end, Cmp cmp = Cmp{})
{
    if (begin == end)
        return end;
    ForwardIt min = begin++;
    for (; begin != end; ++begin)
        if (cmp(*begin, *min))
            min = begin;
    return min;
}
0
Top Sekret On
std::vector<int> myVector = /* ... */;
int min = myVector[0];
for (auto itr = myVector.cbegin (); itr != myVector.cend (); itr ++)
  {
    if (*itr < min)
      min = *itr;
  }

min now contains the smallest value

Simple, effective, working. Iterators are a strength of C++.