0
Help with vector c++
#include <iostream> #include <vector> int main(){ vector<double> vektor{2,3,4,5}; double broj; cout << "Enter number that will be on first place in vector"; cin >> number; vektor.resize(5); for(int i = vektor.size(); i > 0; i--){ double temp = vektor[i-1]; vektor[i] = temp; } vektor[0] = broj; for(auto i : vektor) cout << i << " "; return 0; } When I run this code it results in compilation error Any advice
5 ответов
+ 2
First of all, the code contains dozens of stray characters that look like whitespaces, but aren't. You should rewrite it using another texteditor/ IDE.
Then, you didn't include namespace std, which would be fine if you prefixed everything with std::, but you didn't. Do either one, preferrably the prefixing.
Furthermore, you are asking for 'number' which has not been declared before, I suppose you meant 'broj' there?
And lastly, in the for loop, you are accessing the vector out of bounds, since the size is the number of elements, but vectors are zero-indexed.
Should be everything for now, not sure if there is more.
+ 2
Right now, the vector size equals 5. Since indexing starts at 0, vektor[ vektor.size() ] is out of bounds of the vector, but that is exactly what you are attempting within the for loop. Instead, you hve to start iterating at the index of the last element, meaning the for loop head should look like
for ( int i = vektor.size() - 1; i > 0; --i ) {
// ...
}
+ 1
Just initialize the running variable to
vektor.size() - 1
instead.
0
Thank you for advices but the last one I don't really know what should I do
0
Could you explain me more how to initialize it