Alex Rivera | Logout

Copying std::vector: prefer assignment or std::copy?

Asked 2013-02-20T10:32:13.880
106

I have two vectors:

std::vector<int> v1, v2;

// Filling v1
...

And now I need to copy v1 to v2. Is there any reason to prefer

v2 = v1;

to

std::copy (v1.begin(), v1.end(), v2.begin());

(or vice versa)?

Edit
Report

2 Answers

2

It's shorter.

std::copy is mainly meant for copying sections of containers. If you need to copy an entire container, you might as well use the copy constructor.

answered 2013-02-20T10:35:22.363
1

Assignement is clearer and internally uses std::copy (or unitizalized_copy _M_allocate_and_copy depending size and capacity) or so performances are the same.

answered 2013-02-20T10:46:41.530

Your Answer