About different ways to fill a vector

I can imagine three ways to fill std::vector

Let's pretend that

vector<int> v(100, 0);

Then I want it to hold (1, 1, 1). We can do it:

v.clear();
v.resize(3, 1);

or

v = vector<int>(3, 1);

And I understood a different approach:

vector<int>(3, 1).swap(v); 

First question: is there any better approach?

Second question: suppose what vwas declared outside the main function. In accordance with this answer, the memory will be allocated in the data segment. If I use the second or third approach, will the memory be allocated on the stack?

+5
source share
5 answers

So, here are the differences, and I will let you decide what is best for your situation.

v.clear();
v.resize(3, 1);

. - , , 100 ( , , 100 ). 3 1. reset 3 , - .

v = vector<int>(3, 1);

, , , , 0, 3 , , , memcpy 3 . , v, - 100 .

vector<int>(3, 1).swap(v); 

. , , 1. , 100 , , . . , , . , , , ( v ) , , .

.

+3

, , ?

std::vector<int> v(100);
v.assign(3, 1); // this is what you should do.
+9

: vector , .

, , , .

+2

3 . , , .

vector<int> v(100);
v.assign(3, 1);
assert(v.size() == 3);
assert(v.capacity() != 3);

v = vector<int>(3, 1);
// Now, v.capacity() is likely not to be 3.

vector<int>(3, 1).swap(v);
assert(v.capacity() == 3);

. - 100 * sizeof (int) , size() 3. v.capacity(), .

+1

One of the issues not mentioned in previous posts is important for choosing among these alternatives. Namely: security exceptions. vector<int>(3, 1).swap(v);has a reliable security guarantee. The form v = vector<int>(3, 1);may also offer such a guarantee if the appointment is made in terms of a swap. The first option is unsafe:v.clear(); v.resize(3, 1);

+1
source

All Articles