This looks simple but I am confused: The way I create a vector of hundred, say, int
s is
std::vector<int> *pVect = new std::vector<int>(100);
However, looking at std::vector's documentation I see that its constructor is of the form
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
So, how does the previous one work? Does开发者_高级运维 new
call the constructor with an initialization value obtained from the default constructor? If that is the case, would
std::vector<int, my_allocator> *pVect = new std::vector<int>(100, my_allocator);
where I pass my own allocator, also work?
You are doing it all wrong. Just create it as an automatic object if all you need is a vector in the current scope and time
std::vector<int> pVect(100);
The constructor has default arguments for the second and third parameters. So it is callable with just an int. If you want to pass an own allocator, you have to pass a second argument since you can't just skip it
std::vector<int, myalloc> pVect(100, 0, myalloc(some_params));
A dedicated example might clarify the matter
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.
}
To (perhaps) clarify:
To create a vector object called v of 100 elements:
std::vector <int> v( 100 );
this uses the vector constructor 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 exactly the same constructor.
You are creating a vector
of hundred elements. As you can see in the second code sample you posted:
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
This constructor takes the amount of elements to put into vector
and avalue
which will be inserted into vector n
times. If you do not specify a value
a value
is constructed using default constructor of your vector type T
. Here it would be the "default" constructor of int
which initializes it to 0 (there is no such thing as a default constructor of int
, however C++ standard says that int
is initialized to 0 in such cases).
精彩评论