TheDeveloperBlog.com

Home | Contact Us

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

C++ algorithm remove_copy_if() function

C++ algorithm remove_copy_if() 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_copy_if()

C++ Algorithm remove_copy_if() function is used to copy all elements in the range [first, last) to the range beginning at result, except those elements for which pred returns true 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 removed is remain unchanged.

Syntax

template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator remove_copy_if (InputIterator first, InputIterator last, 
OutputIterator result, UnaryPredicate pred);

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.

result: An output iterator pointing to the initial position of the range to which elements are being removed.

pred: That must be satisfied is the value of an element is to be replaced.

Return value

A forward iterator pointing the new end position (last) of the copied range, which includes all elements in [first, last) except those for which pred will return true.

Complexity

Complexity is linear in the range [first, last): Applies pred to each element, and performs assignment operation for those which are not removed.

Data races

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

The objects in the range between result and the returned value are changed.

Exceptions

This function throws an exception if any of pred, the element assignments or the operations on 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_copy_if():

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

using namespace std;

int main() {
  vector<int> v = { 2,1,3,4,5,7,6,9,8};

  remove_copy_if(v.begin(), v.end(),
    ostream_iterator<int>(cout, ","),
    [](int x) { return x%2 != 0; });
    
    return 0;
}

Output:

2,4,6,8,

Example 2

Let's see another simple example:

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

using namespace std; 
  
bool IsOdd(int i) { 
return ((i % 2) != 0); 
} 
  
// Function to remove from v1 result vector is v2 
void remove_copy_ifDemo(vector <int> &v1, vector<int> &v2) 
{ 
    remove_copy_if(v1.begin(), v1.end(), v2.begin(), IsOdd); 
} 
  
// Function to print content of vector 
void print(vector<int>&v) 
{ 
    int len = v.size(); 

    for (int i = 0; i < len; i++) 
        cout << v[i] << " "; 
    cout << endl; 
} 
   
int main() 
{ 
    // declare vector v1, v2 
    vector <int> v1, v2(10); 
      
    // push data in vector  
    for(int i = 10; i <= 20; i++) 
        v1.push_back(i); 
      
    cout << "elements of v1 before remove_copy: "; 
    print(v1); 
  
remove_copy_ifDemo(v1,v2); 
      
    cout << "elements of v1 after remove_copy: "; 
    print(v1); 
      
cout << "After removing Odd Numbers from v1"
            " copy result in vector v2" <<endl; 
    print(v2); 
  
return 0; 
}

Output:

elements of v1 before remove_copy: 10 11 12 13 14 15 16 17 18 19 20 
elements of v1 after remove_copy: 10 11 12 13 14 15 16 17 18 19 20 
After removing Odd Numbers from v1 copy result in vector v2
10 12 14 16 18 20 0 0 0 0

Example 3

Let's see another simple example:

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

using namespace std;


int main()
{
    const int MAX_ELEMENTS = 8 ;

    // Define a template class vector of integers
    typedef vector<int > IntVector ;

    //Define an iterator for template class vector of integer
    typedef IntVector::iterator IntVectorIt ;

    //vector containing numbers
    IntVector Numbers(MAX_ELEMENTS), Result(MAX_ELEMENTS) ;

    IntVectorIt start, end, it, last, resultIt ;

    //Initialize vector Numbers
    Numbers[0] = 10 ;
    Numbers[1] = 20 ;
    Numbers[2] = 10 ;
    Numbers[3] = 15 ;
    Numbers[4] = 12 ;
    Numbers[5] = 25 ;
    Numbers[6] = 30 ;
    Numbers[7] = 10 ;

    start = Numbers.begin() ;   // location of first
                                // element of Numbers

    end = Numbers.end() ;       // one past the location
                                // last element of Numbers

    resultIt = Result.begin() ; // location of first
                                // element of Result

    // print content of Numbers
    cout << "Numbers { " ;
    for(it = start; it != end; it++)
        cout << *it << " " ;
    cout << " }\n" << endl ;

    // copy all elements from Numbers to Result
    // skipping any item that >= 25
    last = remove_copy_if(start, end, resultIt,
                          bind2nd(greater_equal<int>(), 25)) ;

    //print number of elements copied to Result
    cout << "Total number of elements copied to Result = "
        << last - resultIt << endl ;

    start = Result.begin() ;   // location of first
                                // element of Result

    end = Result.end() ;       // one past the location
                               // last element of Result

    // print content of Result
    cout << "Result { " ;
    for(it = start; it != end; it++)
        cout << *it << " " ;
    cout << " }\n" << endl ;
    
    return 0;
}

Output:

Numbers { 10 20 10 15 12 25 30 10  }

Total number of elements copied to Result = 6
Result { 10 20 10 15 12 10 0 0  }

Example 4

Let's see another simple example:

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

using namespace std;

bool greathan(int value)
{ return value >7;}
 
int main(void)
{
// vector container
vector <int> vec1, vec2(14);

// vector iterator
vector <int>::iterator Iter1, Iter2, new_end;
int i, j;

// push data in range
for(i = 0; i <= 10; i++)
vec1.push_back(i);
for(j = 0; j <= 2; j++)
vec1.push_back(5); 


// print the data
cout<<"The original vec1 vector data: ";
for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)
cout<<*Iter1<<" ";
cout<<endl;

// randomly shuffle the data
random_shuffle(vec1.begin(), vec1.end());
cout<<"\nThe original vec1 vector data randomly shuffled: ";
for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)
cout<<*Iter1<<" ";
cout<<endl;

// remove elements with a value greater than 7

new_end = remove_copy_if(vec1.begin(), vec1.end(), vec2.begin(), greathan);
cout<<"\nAfter the remove_copy_if() operation, the vec1 vector is left unchanged as: ";
for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)
cout<<*Iter1<<" ";
cout<<endl;
cout<<"\nvec2 vector is a copy of vec1 vector with values greater than 7 removed: ";
for(Iter2 = vec2.begin(); Iter2 != new_end; Iter2++)
cout<<*Iter2<<" ";
cout<<endl;

return 0;

}

Output:

The original vec1 vector data: 0 1 2 3 4 5 6 7 8 9 10 5 5 5 

The original vec1 vector data randomly shuffled: 4 10 5 5 0 5 5 1 6 9 3 7 8 2 

After the remove_copy_if() operation, the vec1 vector is left unchanged as: 4 10 5 5 0 5 5 1 6 9 3 7 8 2 

vec2 vector is a copy of vec1 vector with values greater than 7 removed: 4 5 5 0 5 5 1 6 3 7 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