Vector Assign vs Vector operator=

C

Chris Roth

vector<double> v1(5,1);
vector<double> v2;

v2 = v1; // 1
v2.assign(v1.begin(),v1.end()); // 2

Are 1 and 2 the same, or are their subtle differences between them.
Which is preferable, if either? And yes, I know I could use the
construction vector<double> v2(v1), but I'm giving an example above.

Thank you c++ users.
 
J

John Harrison

Chris said:
vector<double> v1(5,1);
vector<double> v2;

v2 = v1; // 1
v2.assign(v1.begin(),v1.end()); // 2

Are 1 and 2 the same, or are their subtle differences between them.
Which is preferable, if either? And yes, I know I could use the
construction vector<double> v2(v1), but I'm giving an example above.

Thank you c++ users.

No observable difference between them, but 1 is clearly better since it
is clearer to any reader of the code. With 2 you have to check the
arguments to understand the meaning.

john
 
R

red floyd

Chris said:
vector<double> v1(5,1);
vector<double> v2;

v2 = v1; // 1
v2.assign(v1.begin(),v1.end()); // 2

Are 1 and 2 the same, or are their subtle differences between them.
Which is preferable, if either? And yes, I know I could use the
construction vector<double> v2(v1), but I'm giving an example above.

As John said, there's probably no detectable difference. The latter
construct (assign) is more useful when you want to copy a subvector.

e.g.:

vector<double> v1;
vector<double> v2;

// fill v1 here.

vector<double>::iterator start_iter = some_iterator_into_v1;
vector<double>::iterator end_iter = some_other_iterator_into_v1;

v2.assign(start_iter, end_iter);
 
J

jlongstreet

As John said, there's probably no detectable difference. The latter
construct (assign) is more useful when you want to copy a subvector.

e.g.:

vector<double> v1;
vector<double> v2;

// fill v1 here.

vector<double>::iterator start_iter = some_iterator_into_v1;
vector<double>::iterator end_iter = some_other_iterator_into_v1;

v2.assign(start_iter, end_iter);

Also, using assign allows you to assign across container types:

vector<int> v;
list<int> ll;

// fill ll here

v.assign(ll.begin(), ll.end());
 
R

Ron Natalie

red said:
As John said, there's probably no detectable difference. The latter
construct (assign) is more useful when you want to copy a subvector.
In case 1, v1 must be a vector.
In case 2, v1 can be anything provided that the iterators returned
are of a type that's insertable into v2.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top