Example 1 — Collapse runs
Copy a vector while collapsing equal neighbours.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> src = {1, 1, 2, 2, 3, 1, 1};
std::vector<int> out;
std::unique_copy(src.begin(), src.end(), std::back_inserter(out));
std::cout << "src size: " << src.size() << '\n';
std::cout << "out: ";
for (int x : out) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
How It Works
- The runs are 1 1, 2 2, 3 and 1 1.
- One value from each run goes into
out. - The last 1 stays because it is not next to the first run.
Example 2 — Squeeze letters
Remove repeated letters from a word.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
int main() {
std::string word = "bookkeeper";
std::string result;
std::unique_copy(word.begin(), word.end(), std::back_inserter(result));
std::cout << result << '\n';
return 0;
}
How It Works
oo, kk and ee are runs of equal letters.- Each run is shortened to one letter.
- The later single
e is not next to the first run, so it stays in the output.
Example 3 — Print directly
Keep the first word for each starting letter and print it.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main() {
std::vector<std::string> words = {"apple", "avocado", "banana", "blueberry", "cherry"};
std::unique_copy(words.begin(), words.end(),
std::ostream_iterator<std::string>(std::cout, " "),
[](const std::string& a, const std::string& b) { return a[0] == b[0]; });
std::cout << '\n';
return 0;
}
How It Works
- The predicate says two words are equal when they start with the same letter.
avocado follows apple, and blueberry follows banana, so they are skipped.std::ostream_iterator sends the kept words straight to the screen.