vector

HI. I have a problem in vector . after insert number in vector when i want to use cout for show vector compiler show another number
1
2
3
////////////////////////cout ////////////////////
0
0
0
1
2
3

main()
{
int num ;
vector<int> SS(3);
cout << "Loop by index:" << endl;
for ( int i = 0 ; i < 3 ; i++)
{
cin >> num;
SS.push_back(num);
}
int ii;
for(ii=0; ii < SS.size(); ii++)
{
cout << SS[ii] << endl;
}
return 0;
When you do: vector<int> SS(3);, the compiler will create a vector like this: {0, 0, 0}

Then when you push_back(), you add the numbers on the END, you don't replace them.
how to solve this problem ?
Don't instantiate the vector with 3 elements.
Seems that jsmith and firedraco well beat me to this.

Don't instantiate the vector with three elements. Just use
vector<int> SS;

Vectors dynamically allocate their storage, unlike arrays. You don't need to and I don't think you can define the maximum size of a vector at initialization.

-Albatross
Last edited on
Topic archived. No new replies allowed.