Call the default constructor for each element in the constructed std :: vector

Is there a way to build std::vector<C> from N elements by calling the default constructor for each?

The constructor from size_type simply calls the C constructor once, and then uses its copy constructor for the rest of the elements.

+5
source share
2 answers

The constructor from size_type simply calls the C constructor once and then uses its copy constructor for the rest of the elements.

Not true, since C++11 . See std :: vector :: vector documentation :

...

vector (size_type count, const T & cost, const Allocator & alloc = Allocator ()); (2)

explicit vector (size_type count, const Allocator & alloc = Allocator ()); (3)

...

And then:

...

2) Creates a container with counted copies of elements with value value.

3) Creates a container with the default value of T. instances. No copies.

...

So you need the third constructor std::vector<C>(size)


It seems that this behavior only exists with C++11 .

I cannot find a way to do this until C++11 . Since the constructor cannot do this, the option would be to create empty vectors, fallback, and then emplace_back elements. But emplace_back has since been C++11 , so ... we will go back to the square.

+5
source

Just do the following:

 std::vector<C> v(size) 

Example:

 #include <iostream> #include <string> #include <vector> class C{ public: C(){ std::cout << "constructor\n"; } C(C const&){ std::cout << "copy/n"; } }; int main() { std::vector<C> v(10); } 

Result: (C ++ 11/14)

 constructor constructor constructor constructor constructor constructor constructor constructor constructor constructor 

Results: (C ++ 98)

 constructor copy copy copy copy copy copy copy copy copy copy 

Live demo

+3
source

Source: https://habr.com/ru/post/1239772/


All Articles