TheDeveloperBlog.com

Home | Contact Us

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

C++ algorithm unique_copy() function

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

C++ Algorithm unique_copy() function is used to copy a sequence such as each duplicate consecutive element becomes a unique element.

  • It will not alter the original range and copy the result into another container.
  • The first version uses operator== to compare the elements and the second version uses the given binary predicate pred.

Syntax

equality (1)	template <class InputIterator, class OutputIterator>
                            OutputIterator unique_copy (InputIterator first, InputIterator last,
                                                 OutputIterator result);

predicate (2)    template <class InputIterator, class OutputIterator, class BinaryPredicate>
                        OutputIterator unique_copy (InputIterator first, InputIterator last,
                                                 OutputIterator result, BinaryPredicate pred);

Parameter

first: A forward iterator pointing the position of the first element in the range to be copied.

last: A forward iterator pointing the position one past the final element in the range to be copied.

pred: A user-defined predicate function object that defines the condition to be satisfied if two elements in a range are to be taken as equivalent. A binary predicate returns two arguments and returns true when satisfied and false when not satisfied.

result: An output iterator pointing the position of the first element in the copied range that is receiving the copy with consecutive duplicates removed.

Return value

An iterator pointing to the new end of the copied range[first, last) that contains no consecutive duplicates.

Complexity

Complexity is linear in the range [first, last): compares each pairs of consecutive elements, and performs assignment operation on some of them.

Data races

The object in the range [first, last) are accessed and the objects in the range between result and the returned value are modified.

Exception safety

This function throws an exception if any of pred, the element comparisons, 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 unique_copy() where elements will be compared by operator==:

#include <iostream> 
#include <vector> 
#include <algorithm> 
using namespace std; 
int main() 
{ 
    vector<int> v = { 100, 100, 300, 300, 300, 500, 100, 
                      300, 300, 600, 600, 700 }; 
  
    // vector to store the copied value 
    vector<int> v1(10); 
  
    vector<int>::iterator ip; 
  
    // Using unique_copy 
    ip = unique_copy(v.begin(), v.begin() + 12, v1.begin()); 
  
    // Resizing vector v1 
    v1.resize(distance(v1.begin(), ip)); 
  
    cout << "Before: "; 
    for (ip = v.begin(); ip != v.end(); ++ip)  
    { 
        cout << *ip << " "; 
    } 
  
    // Displaying vector after applying unique_copy 
    cout << "\n\nAfter:  "; 
    for (ip = v1.begin(); ip != v1.end(); ++ip)  
    { 
        cout << *ip << " "; 
    } 
  
    return 0; 
}

Output:

Before: 100 100 300 300 300 500 100 300 300 600 600 700 

After:  100 300 500 100 300 600 700  

In the above example, all the sub-group of consecutive duplicate elements from vector v have been reduced to only one element and copied to new vector v1.

Example 2

Let's see another simple example to illustrate the use of unique_copy() where elements will be compared by pre-defined function:

#include <iostream> 
#include <algorithm> 
#include <string> 
using namespace std; 
  
// declaring a BinaryFunction 
bool Pred(char a, char b) 
{ 
    // It checks if the both the arguments are same and equal 
    // to 'v' then only they are considered same and duplicates are removed 
    if (a == b && a == 'v')  
    { 
        return 1; 
    }  
    else 
    { 
        return 0; 
    } 
} 
int main() 
{ 
    // Declaring a string 
    string s = "You arre vvvisiting vvvogie bbogie", s1; 
  
    // Using std::unique_copy to remove the consecutive 
    // v in the word and copy it to s1 
    auto ip = unique_copy(s.begin(), s.end(), back_inserter(s1), Pred); 
  
    cout << "Before: " << s; 
  
    // Displaying the corrected string 
    cout << "\nAfter: " << s1; 
    return 0; 
}

Output:

Before: You arre vvvisiting vvvogie bbogie
After: You arre visiting vogie bbogie

Example 3

Let's see another simple example to check whether the container contains duplicates elements or not:

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

using namespace std; 

int main() 
{ 
    vector<int> v = { 1, 4, 3, 5, 2, 7, 6 }; 
  
    vector<int>::iterator ip; 
  
    // Sorting the array to make duplicate elements 
    // consecutive 
    sort(v.begin(), v.end()); 
    // Now v becomes 1 2 3 4 5 6 7 
  
    // Declaring a container to store the unique elements 
    vector<int> v1(7); 
  
    // Using unique_copy 
    ip = unique_copy(v.begin(), v.end(), v1.begin()); 
    // Now v1 becomes {1 2 3 4 5 6 7 } 
  
    if (v == v1)  
    { 
        cout << "v1 contains only unique elements"; 
    }  
    else 
    { 
        cout << "v1 contains duplicate elements"; 
    } 
    return 0; 
} 

Output:

v1 contains only unique elements

In the above example, first we remove the duplicate elements from vector v and store the resultant elements into another vector v1 and then compare the v1 to v, if both are the same. (Means previous vector v contains only unique elements and there is no duplicate element).

Example 4

Let's see another simple example to remove all the spaces from the given statement:

#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>

using namespace std;
 
int main()
{
    string s1 = "The string with many spaces!";
    cout << "before:  " << s1 << '\n';
 
    string s2;
    unique_copy(s1.begin(), s1.end(), std::back_inserter(s2),
                     [](char c1, char c2){ return c1 == ' ' && c2 == ' '; });
 
    cout << "after:   " << s2 << '\n';
}

Output:

before:  The      string    with many       spaces!
after:    The string with many spaces!

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