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
Sort all elements in the range [first, last) into ascending order.
Sort all elements in the range [first, last) into ascending order. sort Header <algorithm> template<class RandomAccessIterator> void sort(RandomAccessIterator first, RandomAccessIterator last) Sort all elements in the range [first, last) into ascending order. The non-predicate version uses operator< for comparison. template<class RandomAccessIterator, class BinaryPredicate> void sort(RandomAccessIterator first, RandomAccessIterator last, BinaryPredicate pr) Sort all elements in the range [first, last) into ascending order. The predicate version uses the predicate function pr for comparison. Sample #pragma warning(disable : 4786) #include <algorithm> #include <iostream> #include <functional> int main() { int array[6] = { 102, 425, 678, 34, 87, 69} ; std::ostream_iterator<int> intOstreamIt(std::cout, ", ") ; std::cout << "using non-predicate sort" << std::endl ; std::cout << "\n\narray before sorting = " ; std::copy(array, array+6, intOstreamIt) ; std::cout << std::endl ; //sort non-predicate version std::sort(array, array+6) ; std::cout << "\n\narray after sorting = " ; std::copy(array, array+6, intOstreamIt) ; std::cout << std::endl ; std::random_shuffle(array, array+6) ; std::cout << "using predicate sort" << std::endl ; std::cout << "\n\narray after random_shuffle = " ; std::copy(array, array+6, intOstreamIt) ; std::cout << std::endl ; //sort predicate version std::sort(array, array+6, std::less<int>()) ; std::cout << "\n\narray after sorting = " ; std::copy(array, array+6, intOstreamIt) ; std::cout << std::endl ; return 0 ; } Program Output using non-predicate sort array before sorting = 102, 425, 678, 34, 87, 69, array after sorting = 34, 69, 87, 102, 425, 678, using predicate sort array after random_shuffle = 425, 102, 34, 87, 678, 69, array after sorting = 34, 69, 87, 102, 425, 678,
Privacy Policy
|
Link to Us
|
Links