hi i am new to c++ and im learning vectors right now and i have learned how to add values to them but starting with some values already in a vector.

so i was wondering if this is good coding practice or bad practice

i have learned that you can do say

 ``123`` ``````vector numbers (2); numbers[0] = 1; numbers[1] = 2;``````

but if i want to start with nothing in the vector and fill it along the way is it good practice to do this or should i always add at least 1 value to a vector

 `` `` ``vector numbers (0);``
 ``12345678910111213141516171819202122232425262728293031323334353637`` ``````#include #include void print( const std::vector& v ) { std::cout << "The vector has " << v.size() << " elements.\n" ; std::cout << "{ " ; for ( auto& element : v ) std::cout << element << ' ' ; // or, if your compiler doesn't support C++11: //for ( std::vector::const_iterator element = v.begin(); element != v.end(); ++element ) // std::cout << *element << ' ' ; std::cout << "}\n" ; } int main() { std::vector vec ; print(vec) ; vec.push_back(1) ; print(vec) ; vec.push_back(2) ; print(vec) ; vec.push_back(-3) ; print(vec) ; vec.push_back(1000) ; print(vec) ; }``````

There is no any sense to define an object of type std::vector the way you showed

vector<int> numbers (0);

This definition is equivalent to

vector<int> numbers;

Also if you define an object of type std::vector this way

vector<int> numbers (2);
numbers[0] = 1;
numbers[1] = 2;

that is you know that the vector will contain at least two elements then it is better to do this the following way

vector<int> numbers;
numbers.resetve( 2 );

numbers.push_back( 1 );
numbers.push_back( 2 );

or

vector<int> numbers = { 1, 2 };

For fundamental types there is no a big difference between your definition and the code I have showed. However if a user defined type is used then it is better to use the definition I have showed because in your case at first the default constructor will be called two times and after that created elemenets of the vector will be overwritten by the copy assignment operator.

ahh thats exactly what i was looking for :D so its better to reserve some space if i know how many values will go in the vector and just push_back on new values that i want to put into it to fill it

thanks a lot guys appreciate the help
Topic archived. No new replies allowed.