Trouble using the header

Asked By 7060 points N/A Posted on -
qa-featured

Hi,

Please check the code I wrote.

The results I get are "0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 "

and what I expected is "0 1 2 3 4 5 6 7 8 9 "

Can anybody explain what the results?

Thanks

 

 

#include <vector>
#include <iostream>
 
using namespace std;
 
int main ()
{
vector <int> A(10);
for (int i = 0 ; i < 10 ; i++)
   A.push_back(i);
for (int i = 0 ; i < A.size() ; i++)
   cout<<A[i]<<" ";
return 0;
}
SHARE
Answered By 0 points N/A #80682

Trouble using the header

qa-featured

You do not need to use as “vector <int> A (10);” it should be as “vector <int> A;”.  When we said it as 10, from the push_bach method occur problem that you faced. That why it printed like that. It will print the answer correctly from the 11th number.

This is the correct coding that can generate your answer.

#include <vector>
#include <iostream>
 
using namespace std;
 
int main ()
{
   
vector <int> A;  

for (int i = 0 ; i < 10 ; i++)
    A.push_back(i);

for (int i = 0 ; i < A.size() ; i++)
   cout<<A[i]<<" ";
return 0;
}

 

I hope this will help you

Related Questions