+ Reply to Thread
Results 1 to 2 of 2

Thread: How to copy n number of elements from vector to list?

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    24

    How to copy n number of elements from vector to list?

    I need to copy n number of elements from vector to list.

    How to do it using STL in C++.

    Currently I am doing as follows:

    Code:
    void MyCopy()
    {
    	std::vector<int> vecInts ;
    
    	vecInts.push_back(10) ;
    	vecInts.push_back(20) ;
    	vecInts.push_back(30) ;
    	vecInts.push_back(40) ;
    	vecInts.push_back(50) ;
    
    	std::list<int> myList ;
    
    	std::vector<int>::iterator itr = vecInts.begin() ;
    	for (; itr != vecInts.end(); itr++)
    	{
    		myList.push_back(*itr) ;
    	}
    }
    Is it correct way?

  2. #2
    Following can be an alternative:

    Code:
    void CopyElements()
    {
    	std::vector<int> vecInts1 ;
    
    	vecInts1.push_back(10) ;
    	vecInts1.push_back(20) ;
    	vecInts1.push_back(30) ;
    	vecInts1.push_back(40) ;
    	vecInts1.push_back(50) ;
    
    	std::list<int> myList1(vecInts1.begin(), vecInts1.begin() + 3) ;
    
    	std::list<int>::iterator itr = myList1.begin() ;
    	for (; itr != myList1.end(); itr++)
    	{
    		char szMessage[100] ;
    		sprintf(szMessage, "Data = %d\n", *itr) ;
    		OutputDebugString(szMessage) ;
    	}
    }

+ 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