Jump to content
  • Advertisement

Archived

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

JoeZ

Vector Copy

This topic is 5823 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
Definitly. I believe copy ( vector1.begin (), vector1.end (), vector 2.begin () ) should do it. Check any of the reference sites to find other methods.

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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!