+ Reply to Thread
Results 1 to 2 of 2

Thread: I want to remove elements having value X from vector. How can I do this?

  1. #1

    I want to remove elements having value X from vector. How can I do this?

    I want to remove elements having value X from vector.

    I am doing exactly below:

    Code:
    void RemoveElements()
    {
    	std::vector<int> elements ;
    
    	elements.push_back(1) ;
    	elements.push_back(3) ;
    	elements.push_back(3) ;
    	elements.push_back(3) ;
    	elements.push_back(4) ;
    
    	//I want to remove elements having value 3. How can I do this?
    	std::remove(elements.begin(), elements.end(), 3) ;
    
    	std::vector<int>::iterator itr = elements.begin() ;
    	char message[100] ;
    	for(; itr != elements.end(); itr++)
    	{
    		sprintf(message, "data %d.\n", *itr) ;
    		OutputDebugString(message) ;
    	}
    }
    Above example does not remove elements from the vector!

    How to do this?

  2. #2
    Junior Member
    Join Date
    May 2012
    Posts
    29
    You will need to use erase and remove both!

    std::remove just returns an iterator points to the element range matching your specified value.

    While erase actually deletes elements from the vector.

    Code:
    void RemoveElements()
    {
    	std::vector<int> elements ;
    
    	elements.push_back(1) ;
    	elements.push_back(3) ;
    	elements.push_back(3) ;
    	elements.push_back(3) ;
    	elements.push_back(4) ;
    
    	elements.erase(std::remove(elements.begin(), elements.end(), 3), elements.end()) ;
    
    	std::vector<int>::iterator itr = elements.begin() ;
    	char message[100] ;
    	for(; itr != elements.end(); itr++)
    	{
    		sprintf(message, "data %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