Skip to content
This repository has been archived by the owner on Nov 8, 2023. It is now read-only.

Algorithm: Edit unique_copy #708

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 47 additions & 11 deletions algorithm/unique_copy.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,53 @@
# unique_copy

**Description** : Copies the elements from the range (first, last), to another range beginning at d_first in such a way that there are no consecutive equal elements. Only the first element of each group of equal elements is copied.
**Description** :std::unique_copy is a function from the C++ standard library's algorithm library that creates a new range of elements by copying only the unique elements from the input range while removing consecutive duplicates. It retains the relative order of the unique elements by copying only the first occurrence of each element.

**Example**:
```cpp
std::string s1 = "The string with many spaces!";
std::cout << "before: " << s1 << '\n';

std::string s2;
std::unique_copy(s1.begin(), s1.end(), std::back_inserter(s2),
[](char c1, char c2){ return c1 == ' ' && c2 == ' '; });

std::cout << "after: " << s2 << '\n';
#include <iostream>
#include <vector>
#include <algorithm>

int main() {

/*------- Number Example----------*/

std::vector<int> numbers{1, 2, 3, 4, 4, 3, 7, 8, 9, 10};

std::vector<int> uniqueNumbers;
std::unique_copy(numbers.begin(), numbers.end(), std::back_inserter(uniqueNumbers));
//The std::back_inserter iterator is used to append the copied elements to uniqueNumbers.


std::cout << "Original numbers: ";
for (const auto& num : numbers) {
std::cout << num << " ";
}

std::cout << "\nUnique numbers: ";
for (const auto& uniqueNum : uniqueNumbers) {
std::cout << uniqueNum << " ";
}

/*------- Word Example----------*/

std::vector<std::string> words{"apple", "banana", "banana", "cherry", "apple", "banana"};

std::vector<std::string> uniqueWords;
std::unique_copy(words.begin(), words.end(), std::back_inserter(uniqueWords));
// The std::back_inserter iterator is used to append the copied elements to uniqueWords

std::cout << "\nOriginal words: ";
for (const auto& word : words) {
std::cout << word << " ";
}

std::cout << "\nUnique words: ";
for (const auto& uniqueWord : uniqueWords) {
std::cout << uniqueWord << " ";
}

return 0;
}
```
**[See Sample code](../snippets/algorithm/unique_copy.cpp)**
**[Run Code](https://rextester.com/WNYDV49783)**
**[Run Code](https://onecompiler.com/cpp/3za2p5k34)**