Which constructor std :: vector is used in this case

It looks simple, but I'm confused: the way to create a vector from hundreds, say int ,

 std::vector<int> *pVect = new std::vector<int>(100); 

However, looking at the std :: vector documentation , I see that its constructor has the form

 explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() ); 

So how does the previous one work? Does new constructor with the initialization value obtained from the default constructor? If so, then

 std::vector<int, my_allocator> *pVect = new std::vector<int>(100, my_allocator); 

where do I transfer my own dispenser, also work?

+7
c ++ stl stdvector
source share
3 answers

You are doing everything wrong. Just create it as an automatic object if all you need is a vector in the current area and time

 std::vector<int> pVect(100); 

The constructor has default arguments for the second and third parameters. Thus, it can only be called with int. If you want to pass your own dispenser, you need to pass the second argument, since you cannot just skip it

 std::vector<int, myalloc> pVect(100, 0, myalloc(some_params)); 

The above example may clarify the issue.

 void f(int age, int height = 180, int weight = 85); int main() { f(25); // age = 25, height and weight taken from defaults. f(25, 90); // age=25, height = 90 (oops!). Won't pass a weight! f(25, 180, 90); // the desired call. } 
+14
source share

To (possibly) clarify:

To create a vector object named v with 100 elements:

 std::vector <int> v( 100 ); 

a vector constructor is used that takes the size (100) as the first parameter. To create a dynamically allocated vector of 100 elements:

 std::vector <int> * p = new std::vector<int>( 100 ); 

which uses the exact same constructor.

+6
source share

You create vector from one hundred elements. As you can see in the second code example that you posted:

explicit vector (size_type n, const & value = T (), const Allocator & sign is equal to Allocator ());

This constructor takes the number of elements placed in vector and value , which will be inserted into the vector n times. If you do not specify value , then a value will be constructed using the default constructor of your vector type T Here it will be the default constructor int , which initializes it to 0 (there is no such thing as the default constructor int , however, the C ++ standard says that int is initialized to 0 in such cases).

0
source share

All Articles