Archived

This topic is now archived and is closed to further replies.

JoeZ

Vector Copy

Recommended Posts

Hi: I just want to know if STL provides a function to copy the contents from one vector to another vector. for example vector <Points> p1,p2 how to copy the points in p1 to p2 without using a loop copying the items one by one. Thank you. [edit: fixed < >'s] [edited by - Magmai Kai Holmlor on August 12, 2002 7:08:44 PM]

Share this post


Link to post
Share on other sites
The post above is correct, but only works if the destination vector already has enough room. It also leaves any extra elements in there. You probably just want to do this:

p2 = p1;

Or if you want to copy the items across to the end of p2, without erasing what is already in there, do this:

p2.insert(p2.end(), p1.begin(), p2.end());

(This will potentially be faster than a copy with a back inserter as the insert can resize the destination vector for you all at once rather than a bit each time.)

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost | Asking Questions | Organising code files | My stuff ]

Share this post


Link to post
Share on other sites
If you want to completely obliterate the contents of the first vector (e.g. you don't wish to append), you can use vector::assign, which is a lot like the assignment operator above, but can let you describe a subset of the source array.

A quick tip about STL (thanks to Scott Meyers): use std::copy as your last resort. Always prefer to use the container member functions first, especially the range versions of the functions--the function knows more about the containers involved and can therefore generate more efficient code.

[edited by - Stoffel on August 12, 2002 4:32:28 PM]

Share this post


Link to post
Share on other sites