C++ Codes
Algorithms
Algorithm Analysis in C++
Beginners
Code Snippets
Graphics
Data Structures
File Manipulation
Games
Mathematics
Miscellaneous
Visual C++ Library
C++ > Visual C++ 5.0 Standard C++ Library sample source codes
Unique - Replace all consecutive matching occurences of a value in the range
Unique - Replace all consecutive matching occurences of a value in the range unique Header <algorithm> template<class ForwardIterator> ForwardIterator unique(ForwardIterator first, ForwardIterator last) Replace all consecutive matching occurences of a value in the range [first, last) by a single instance of that value. Returns an iterator positioned immediately after the last element of the new sequence. The non-predicate version uses operator== for comparison. template<class ForwardIterator, class BinaryPredicate> ForwardIterator unique(ForwardIterator first, ForwardIterator last, BinaryPredicate pr) Replace all consecutive matching occurences of a value in the range [first, last) by a single instance of that value. Returns an iterator positioned immediately after the last element of the new sequence. The predicate version uses predicate function pr for comparison. NOTE: The size of the container is not altered. If n elements were removed the last n elements of the sequence will be undefined. Sample #pragma warning(disable : 4786) #include <algorithm> #include <iostream> #include <functional> #include <vector> int main() { std::vector<int> vi1(10), vi2(10) ; std::vector<int>::iterator last ; vi1[0] = 1 ; vi1[1] = 1 ; vi1[2] = 2 ; vi1[3] = 2 ; vi1[4] = 3 ; vi1[5] = 3 ; vi1[6] = 4 ; vi1[7] = 4 ; vi1[8] = 5 ; vi1[9] = 5 ; std::transform(vi1.begin(), vi1.end(), vi2.begin(), std::negate<int>() ) ; std::ostream_iterator<int> intOstreamIt(std::cout, ", ") ; std::cout << "using non-predicate version" << std::endl ; std::cout << "\n\nvi1 before unique = " ; std::copy(vi1.begin(), vi1.end(), intOstreamIt) ; std::cout << std::endl ; //remove all duplicates from vi1 //using non-predicate version last = std::unique(vi1.begin(), vi1.end()) ; std::cout << "\n\nvi1 after unique = " ; std::copy(vi1.begin(), last, intOstreamIt) ; std::cout << std::endl ; std::cout << "\n\nusing predicate version" << std::endl ; std::cout << "\n\nvi2 before unique = " ; std::copy(vi2.begin(), vi2.end(), intOstreamIt) ; std::cout << std::endl ; //remove all duplicates from vi2 //using predicate version last = std::unique(vi2.begin(), vi2.end(), std::equal_to<int>()) ; std::cout << "\n\nvi2 after unique = " ; std::copy(vi2.begin(), last, intOstreamIt) ; std::cout << std::endl ; return 0 ; } Program output using non-predicate version vi1 before unique = 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, vi1 after unique = 1, 2, 3, 4, 5, using predicate version vi2 before unique = -1, -1, -2, -2, -3, -3, -4, -4, -5, -5, vi2 after unique = -1, -2, -3, -4, -5,
Privacy Policy
|
Link to Us
|
Links