Thread: Quick vector copy

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    6

    Quick vector copy

    Hi, what is the quickest (most processor efficient) way of copying from one vector to another?

    thanks.

  2. #2
    Moderately Rabid Decrypt's Avatar
    Join Date
    Feb 2005
    Location
    Milwaukee, WI, USA
    Posts
    300
    Do you want to copy the entire vector, or just a part of it?
    There is a difference between tedious and difficult.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    6
    The entire vector is all I need.

    I'm currently copying it all using a loop and pushing each item from the source vector to the target vector one at a time - but I'm trying to optimize my code.

    thanks,

  4. #4
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    Code:
    #include<vector>
    #include<iostream>
    using namespace std;
    
    int main()
    {
    	vector<int> v1;
    	v1.push_back(10);
    	v1.push_back(5);
    	v1.push_back(9);
    	// You can initialize a vector from another
    	vector<int>v2(v1);
    	// You can assign a vector to another
    	vector<int> v3;
    	v3 = v2;
    	
    	cout << v3[0] << ", " << v3[1] << ", " << v3[2] << endl;
            // outputs: 10, 5, 9
    }
    Last edited by Darryl; 12-06-2005 at 09:47 AM.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    If you won't need your source vector after the copy, the quickest way is to use swap because it doesn't actually copy anything.
    Code:
    v1.swap(v2);
    Otherwise, initialization or assignment as Darryl showed is the best way (assuming both vectors hold the same type).

  6. #6
    Registered User
    Join Date
    Nov 2005
    Posts
    6
    that's great - thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strcmp returning 1...
    By Axel in forum C Programming
    Replies: 12
    Last Post: 09-08-2006, 07:48 PM
  2. Do you know...
    By davejigsaw in forum C++ Programming
    Replies: 1
    Last Post: 05-10-2005, 10:33 AM
  3. Questions on basic Quick Sort
    By Weng in forum C++ Programming
    Replies: 4
    Last Post: 12-16-2003, 10:06 AM
  4. Quick Sort Help
    By NavyBlue in forum C Programming
    Replies: 1
    Last Post: 03-02-2003, 10:34 PM
  5. Replies: 0
    Last Post: 04-30-2002, 07:24 PM