ARTICLE AD BOX
I am trying to insert elements into a std::vector using push_back() inside a loop, but the vector is not storing values as expected.
Problem
I expect the vector to store all values added inside the loop, but it either stores incorrect values or appears empty when accessed later.
Code
#include <iostream> #include <vector> using namespace std; int main() { vector<int> v; for(int i = 0; i < 5; i++) { v.push_back(i); } for(int i = 0; i < v.size(); i++) { cout << v[i] << " "; } return 0; }Expected Output
0 1 2 3 4Actual Output
(Output is not as expected or vector appears empty)
What I Tried
Checked loop conditions
Verified vector initialization
Ensured push_back() is being called inside the loop
I am unsure why push_back() is not behaving as expected. Is there something I might be missing regarding vector usage inside loops?
