There is a vector with the specified size:

const int N=5; vector<int>a(N); 

I fill the vector with push_back;

 for (int i=0;i<N;++i) { a.push_back(i+2); } for (int i:a) { cout<<i<<" "; } 

Displays N zeros, and the elements themselves: 0 0 0 0 0 2 3 4 5 6 How to get rid of zeros?

    2 answers 2

    Here it is:

     vector<int>a(N); 

    you create a vector originally filled with N null elements. Replace line with

     vector<int>a; 

    and everything will turn out :)

      You fill the vector twice. First, the constructor creates N elements, and then you add another N elements in the loop. It makes sense to create an empty vector, reserving space for all elements.

       ::std::size_t const items_count{5}; ::std::vector<int> items{}; a.reserve(items_count); ::std::size_t item_index{}; for ( item_index = ::std::size_t{0}; items_count != item_index; ++item_index ) { items.emplace_back(static_cast<int>(item_index + ::std::size_t{2})); }