How can I find the minimum value from a vector?
int main() { int v[100] = {5,14,2,4,6}; int n = 5; int mic = v[0]; for(int i=0;i<v[n];i++) { if(v[i]<mic) mic=v[i]; } cout<<mic; }
But is not working, what can I do?
You can use max_element to get the maximum value in vector. The max_element returns an iterator to largest value in the range, or last if the range is empty. As an iterator is like pointers (or you can say pointer is a form of iterator), you can use a * before it to get the value.
Min or Minimum element can be found with the help of *min_element() function provided in STL. Max or Maximum element can be found with the help of *max_element() function provided in STL.
std::min_element(vec.begin(), vec.end())
- for std::vectorstd::min_element(v, v+n)
- for arraystd::min_element( std::begin(v), std::end(v) )
- added C++11 version from comment by @JamesKanze
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With