What's wrong with my code [?]
Honestly, almost everything.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
using namespace std;
can cause harm, not in small examples like this, but better don't get used to bad habits.
int main()
{
int a[999];
You allocate space for 999 elements. What if the user enters 1000
for n
?
int n;
cin >> n;
Array indices start at 0
not at 1
. Lets say the user enters 999
then you are still going out of bounds invoking undefined behaviour because a[999]
is not an element of the array.
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
You are calling the std::vector
constructor that sizes the vector to hold a[1]
elements with value a[n]
. This is not copying the elements from the array to the vector! All elements will have the same value, hence you always get 0
as the result.
vector<int> arr(a[1], a[n]);
int max = *max_element(arr.begin(), arr.end());
int min = *min_element(arr.begin(), arr.end());
This is not really wrong, but written unnecessarily complicated. max_element
returns an iterator and you can use eg. std::distance
to get the distance between two iterators.
int dis = max - min; cout << dis << endl;
return 0;
}
You could write it like this
#include<iostream>
#include<algorithm>
#include<vector>
int main()
{
std::vector<int> x;
int n;
std::cin >> n;
x.resize(n);
for (auto& e : x) std::cin >> e;
auto max = std::max_element(x.begin(), x.end());
auto min = std::min_element(x.begin(), x.end());
std::cout << std::distance(max,min) << "\n";
return 0;
}
Live Demo
PS: Be careful with std::distance
. Prior to C++11 it was undefined behaviour to call it with a second argument that cannot be reached from the first iterator passed by going forward. Also note that there is std::minmax_element
that will give you both iterators from only traversing the vector once.