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
Algorithm search n searches for a sequence of equal values.
Algorithm search n searches for a sequence of equal values. search_n Header <algorithm> template<class ForwardIterator, class Size, class T> ForwardIterator search_n(ForwardIterator first1, ForwardIterataor last1, Size count, const T& value) search_n searches for a sequence of equal values. The count argument tells search_n how many consecutive copies of value to look for. It returns an iterator pointing to the start of the subsequence, or last if no subsequence of equal values was found. The non-predicate version uses operator== for comparison. template<class ForwardIterator, class Size, class T, class BinaryPredicate> ForwardIterator search_n(ForwardIterator first1, ForwardIterataor last1, Size count, const T& value, BinaryPredicate pr) search_n searches for a sequence of equal values. The count argument tells search_n how many consecutive copies of value to look for. It returns an iterator pointing to the start of the subsequence, or last if no subsequence of equal values was found. The predicate version uses predicate function pr for comparison. Sample #pragma warning(disable : 4786) #include <algorithm> #include <iostream> #include <functional> int main() { int array[7] = {1, 2, 3, 3, 4, 4, 5 } ; int *pi ; std::ostream_iterator<int> intOstreamIt(std::cout, ", ") ; std::cout << "array = " ; std::copy(array, array+7, intOstreamIt) ; std::cout << std::endl ; //non-predicate version of search_n //search if 2 copies of value 3 exists in array //if found return the position of the last //copy of 3 in array. pi = std::search_n(array, array+7, 2, 3) ; std::cout << "\n \nusing non-predicate version of search_n" << std::endl ; if (pi != array+7) std::cout << "found 2 copies of element 3 in array" << std::endl ; else std::cout << "array does not contain 2 copies of element 3" << std::endl ; //predicate version of search_n //search if 2 copies of value 3 exists in array //if found return the position of the last //copy of 3 in array. pi = std::search_n(array, array+7, 2, 4, std::equal_to<int>()) ; std::cout << "\n \nusing predicate version of search_n" << std::endl ; if (pi != array+7) std::cout << "found 2 copies of element 4 in array" << std::endl ; else std::cout << "array does not contain 2 copies of element 3" << std::endl ; return 0 ; } Program Output array = 1, 2, 3, 3, 4, 4, 5, using non-predicate version of search_n found 2 copies of element 3 in array using predicate version of search_n found 2 copies of element 4 in array
Privacy Policy
|
Link to Us
|
Links