+ Reply to Thread
Results 1 to 2 of 2

Thread: How to Copy elements from one vector to another vector?

  1. #1

    How to Copy elements from one vector to another vector?

    I have following code:

    Code:
    void CopyItems()
    {
        std::vector<int> items1 ;
    
        items1.push_back(111) ;
        items1.push_back(222) ;
        items1.push_back(333) ;
        
        std::vector<int> items2 ;
    
        std::vector<int>::iterator itr = items1.begin() ;
        for(; itr != items1.end(); itr++)
        {
            items2.push_back(*itr) ;
        }
    
        char message[100] ;
        itr = items2.begin() ;
        for(; itr != items2.end(); itr++)
        {
            sprintf(message, "item %d.\n", *itr) ;
            OutputDebugString(message) ;
        }
    }
    I am iterating though vector 1 and copy its data to another vector.

    Is there any nice way than this to copy elements from one vector to another?

    Any help will be appreciated!
    Last edited by Rose; 05-17-2012 at 09:54 AM.

  2. #2
    Use one of the below described approaches:
    Code:
    void CopyItems()
    {
    	std::vector<int> items1 ;
    
    	items1.push_back(111) ;
    	items1.push_back(222) ;
    	items1.push_back(333) ;
    	
    	//Approach 1:
    	std::vector<int> items2(items1.begin(), items1.end()) ;
    
    	char message[100] ;
    	std::vector<int>::iterator itr = items2.begin() ;
    	for(; itr != items2.end(); itr++)
    	{
    		sprintf(message, "item %d.\n", *itr) ;
    		OutputDebugString(message) ;
    	}
    
    	items2.clear() ;
    
    	//Approach 2:
    	items2.resize(items1.size()) ;
    
    	std::copy(items1.begin(), items1.end(), items2.begin()) ;
    	
    	itr = items2.begin() ;
    	for(; itr != items2.end(); itr++)
    	{
    		sprintf(message, "item %d.\n", *itr) ;
    		OutputDebugString(message) ;
    	}
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts