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

27th Aug 2019, 6:52 PM
Senudin
Senudin - avatar
5 Réponses
+ 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.
27th Aug 2019, 7:02 PM
Shadow
Shadow - avatar
+ 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 ) { // ... }
29th Aug 2019, 10:08 AM
Shadow
Shadow - avatar
+ 1
Just initialize the running variable to vektor.size() - 1 instead.
27th Aug 2019, 8:16 PM
Shadow
Shadow - avatar
0
Thank you for advices but the last one I don't really know what should I do
27th Aug 2019, 8:08 PM
Senudin
Senudin - avatar
0
Could you explain me more how to initialize it
28th Aug 2019, 1:53 PM
Senudin
Senudin - avatar