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 Answers
+ 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