+ Reply to Thread
Results 1 to 2 of 2

Thread: Why std::copy does not work after vector::reserve call in C++?

  1. #1

    Why std::copy does not work after vector::reserve call in C++?

    I have following code:

    Code:
    void Fun1()
    {
    	std::vector<int> vInts1;
    
    	vInts1.push_back(11) ;
    	vInts1.push_back(22) ;
    	vInts1.push_back(33) ;
    
    	std::vector<int> vInts2 ;
    	vInts2.reserve(3) ;
    
    	std::copy(vInts1.begin(), vInts1.end(), vInts2.begin()) ;
    
    	std::vector<int>::iterator itr = vInts2.begin() ;
    	for (; itr != vInts2.end(); itr++)
    	{
    		char szMessage[1024] ;
    		sprintf(szMessage, "Data : %d\n", *itr) ;
    		OutputDebugString(szMessage) ;
    	}
    }
    After I make a call to reserve, I copy content of one vector to another.

    But, it prints nothing!

    Why?

    Please help.

  2. #2
    Use 'resize' instead of 'reserve'.

    Example:

    Code:
    void Fun1()
    {
    	std::vector<int> vInts1;
    
    	vInts1.push_back(11) ;
    	vInts1.push_back(22) ;
    	vInts1.push_back(33) ;
    
    	std::vector<int> vInts2 ;
    	vInts2.resize(3) ;
    
    	std::copy(vInts1.begin(), vInts1.end(), vInts2.begin()) ;
    
    	std::vector<int>::iterator itr = vInts2.begin() ;
    	for (; itr != vInts2.end(); itr++)
    	{
    		char szMessage[1024] ;
    		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