about vectors

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

1
2
3
vector<int> 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<int> numbers (0);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <vector>
#include <iostream>

void print( const std::vector<int>& 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<int>::const_iterator element = v.begin(); element != v.end(); ++element )
     //    std::cout << *element << ' ' ;

    std::cout << "}\n" ;
}


int main()
{
    std::vector<int> 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) ;
}


http://www.cplusplus.com/reference/vector/vector/ may be helpful.
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.