TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C++ algorithm remove() function

C++ algorithm remove() function with c++ tutorial for beginners and professionals with examples on adjacent_find(),any_of(), copy(), copy_if(), count(), count_if(), equal(), find(), find_end(), find_first_of(), find_if(), find_if_not(), for_each() etc.

<< Back to CPP

C++ Algorithm remove()

C++ Algorithm remove() function is used to eliminate all the elements that are equal to val from a given range [first, last) without disturbing the order of the remaining elements.

  • This function cannot alter the size of the container.
  • It returns an iterator to the new end of the range.
  • Remove is stable, means that the relative order of the elements that are not equal to val is remain unchanged.
  • This function uses operator== to compare the individual elements to val.

Syntax

template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);

Parameter

first: A forward iterator pointing the position of the first element in the range from which elements are being removed.

last: A forward iterator pointing the position one past the final element in the range from which elements are being removed.

val: A value that is to be removed from the range.

Return value

A forward iterator pointing the new end position (last) of the modified range or first element if first and last is equal.

Complexity

Complexity is linear in the range [first, last) and possibly performs an assignments on some of them.

Data races

The object in the range [first, last) are accessed and potentially modified.

Exception safety

This function throws an exception if any of the element comparisons, element assignments or the operation on an iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of remove():

#include <iostream>     // std::cout
#include <algorithm>    // std::remove

using namespace std;

int main () {
  int myints[] = {10,20,30,50,20,40,100,20};   

  // bounds of range:
  int* pbegin = myints;                          
  int* pend = myints+sizeof(myints)/sizeof(int); 

  pend = remove (pbegin, pend, 20);        
                                                 
  cout << "range contains:";
  for (int* p=pbegin; p!=pend; ++p)
    cout << ' ' << *p;
  cout << '\n';

  return 0;
}

Output:

range contains: 10 30 50 40 100

Example 2

Let's see another simple example to illustrate the difference between erase() and remove():

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
	using namespace std;

	//Populate myvec with the data set 10, 5, -8, 5, 1, 4
	vector<int> myvec;
	myvec.push_back(10);
	myvec.push_back(5);
	myvec.push_back(-8);
	myvec.push_back(5);
	myvec.push_back(1);
	myvec.push_back(4);

	cout << "\n Initial data set:	";
	for(size_t i(0); i!=myvec.size(); ++i)
		cout << myvec.at(i) << ' ';

	//Remove the data elements matching '5'
	vector<int>::iterator invalid;
	invalid = remove( myvec.begin(), myvec.end(), 5 );

	cout << "\n\n Data set after remove: ";
	for(size_t i(0); i!=myvec.size(); ++i)
		cout << myvec.at(i) << ' ';

	//Destroy the remaining invalid elements
	myvec.erase( invalid, myvec.end() );

	cout << "\n\n Data set after erase:  ";
	for(size_t i(0); i!=myvec.size(); ++i)
		cout << myvec.at(i) << ' ';
		
		return 0;
}

Output:

  Initial data set:	10 5 -8 5 1 4 

 Data set after remove: 10 -8 1 4 1 4 

 Data set after erase:  10 -8 1 4  

Example 3

Let's see another simple example:

#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

bool IsOdd(int i) 
{ 
    return ((i % 2) == 1); 
} 
  
// Driver code 
int main ()  
{ 
    vector <int> vec1 { 10, 20, 30, 30, 20, 10, 10, 20}; 
      
    // Print original vector 
    cout << "Original vector : "; 
    for(int i=0; i < vec1.size(); i++) 
        cout << " " << vec1[i]; 
    cout << "\n"; 
  
    // Iterator that store the position of last element 
    vector <int>::iterator pend; 
      
    // std ::remove function call 
    pend = remove (vec1.begin(), vec1.end() , 20); 
      
    // Print the vector 
    cout << "After remove : "; 
    for ( vector<int> :: iterator p=vec1.begin(); p != pend; ++p) 
        cout << ' ' << *p; 
    cout << '\n'; 
    
    return 0;
}

Output:

Original vector :  10 20 30 30 20 10 10 20
After remove :  10 30 30 10 10

Example 4

Let's see another simple example:

#include <vector>  
#include <algorithm>  
#include <iostream>  
  
int main( ) {  
   using namespace std;  
   vector <int> v1;  
   vector <int>::iterator Iter1, Iter2, new_end;  
  
   int i;  
   for ( i = 0 ; i <= 9 ; i++ )  
      v1.push_back( i );  
  
   int ii;  
   for ( ii = 0 ; ii <= 3 ; ii++ )  
      v1.push_back( 7 );  
  
   random_shuffle ( v1.begin( ), v1.end( ) );  
   cout << "Vector v1 is ( " ;  
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )  
      cout << *Iter1 << " ";  
   cout << ")." << endl;  
  
   // Remove elements with a value of 7  
   new_end = remove ( v1.begin( ), v1.end( ), 7 );  
  
   cout << "Vector v1 with value 7 removed is ( " ;  
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )  
      cout << *Iter1 << " ";  
   cout << ")." << endl;  
  
   // To change the sequence size, use erase  
   v1.erase (new_end, v1.end( ) );  
  
   cout << "Vector v1 resized with value 7 removed is ( " ;  
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )  
      cout << *Iter1 << " ";  
   cout << ")." << endl; 
   
   return 0;
}

Output:

Vector v1 is ( 4 7 7 7 0 5 7 1 6 9 3 7 8 2 ).
Vector v1 with value 7 removed is ( 4 0 5 1 6 9 3 8 2 9 3 7 8 2 ).
Vector v1 resized with value 7 removed is ( 4 0 5 1 6 9 3 8 2 ).

Next TopicC++ Algorithm




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf