#include <iostream>
#include <vector>
#include <algorithm> // std::min_element
#include <iterator> // std::begin, std::end
int main() {
std::vector<int> v = {5,14,2,4,6};
auto result = std::min_element(std::begin(v), std::end(v));
if (std::end(v)!=result)
std::cout << *result << '\n';
}
The program you show has a few problems, the primary culprit being the for
condition: i<v[n]
. You initialize the array, setting the first 5 elements to various values and the rest to zero. n
is set to the number of elements you explicitly initialized so v[n]
is the first element that was implicitly initialized to zero. Therefore the loop condition is false the first time around and the loop does not run at all; your code simply prints out the first element.
Some minor issues:
avoid raw arrays; they behave strangely and inconsistently (e.g., implicit conversion to pointer to the array's first element, can't be assigned, can't be passed to/returned from functions by value)
avoid magic numbers. int v[100]
is an invitation to a bug if you want your array to get input from somewhere and then try to handle more than 100 elements.
avoid using namespace std;
It's not a big deal in implementation files, although IMO it's better to just get used to explicit qualification, but it can cause problems if you blindly use it everywhere because you'll put it in header files and start causing unnecessary name conflicts.