Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: std::vector::resize vs. "normal" allocation

In the code example for std::transform, there is an example with code like this:

std::vector<int> foo;
std::vector<int> bar;

//add some elements to foo

bar.resize(foo.size());

//store elements transformed from foo's in bar

And I was wondering whether

std::vector<int> bar;    
bar.resize(foo.size());

was any different from

std::vector<int> bar(foo.size());

and if so, how?

like image 409
User1291 Avatar asked Sep 25 '26 09:09

User1291


2 Answers

No, there's no difference. At least not in the way you show it (with no insertions into foo between the definition of bar and the call to resize).

like image 144
Some programmer dude Avatar answered Sep 27 '26 00:09

Some programmer dude


No difference, except that the latter is a tiny bit more efficient and concise.

like image 36
emlai Avatar answered Sep 27 '26 00:09

emlai