Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding minimum element in array using STL in C++

Tags:

c++

stl

Why the output is coming to be 50 it should have been 20.

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
  int v[] = {10, 20, 30, 50, 20, 70, 30};

  int* i1;
  i1 = std::min_element(v + 3, v + 4);

  cout << *i1 << "\n";
  return 0;
}
like image 601
Rajesh Shaw Avatar asked Oct 09 '19 08:10

Rajesh Shaw


People also ask

How do you find the index of Max element in an array in STL?

Find Maximum value in Array using STL function max_element() and find() To find the max value use max_element(). It returns an iterator or address of the largest value in the range. To find the index position of an element use find().

How do you find the minimum value in C?

C program to find smallest number in an array If the minimum occurs two or more times in the array then the index at which it occurs first is printed or minimum value at the smallest index. You can modify the code to print the largest index at which the minimum occurs.


1 Answers

STL algorithms operate on half-open ranges, which are usually denoted as [first, last). This means the first element is included in the range, the last element is not included. Hence

[v + 3, v + 4)

specifies a range of length 1, and the only element in that range has the value 50.The result of *std::min_element(v + 3, v + 4) can be nothing but 50.

like image 126
lubgr Avatar answered Nov 15 '22 05:11

lubgr