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
Stable sort - Sort all elements in the range [first, last) into ascending order.
Stable sort - Sort all elements in the range [first, last) into ascending order. stable_sort Header <algorithm> template<class RandomAccessIterator> void sort(RandomAccessIterator first, RandomAccessIterator last) Sort all elements in the range [first, last) into ascending order. The relative order of equal elements is preserved. 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 relative order of equal elements is preserved. 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, 102, 34, 87, 34} ; std::ostream_iterator<int> intOstreamIt(std::cout, ", ") ; std::cout << "using non-predicate stable_sort" << std::endl ; std::cout << "\n\narray before sorting = " ; std::copy(array, array+6, intOstreamIt) ; std::cout << std::endl ; //stable_sort non-predicate version std::stable_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 stable_sort" << std::endl ; std::cout << "\n\narray after random_shuffle = " ; std::copy(array, array+6, intOstreamIt) ; std::cout << std::endl ; //sort predicate version std::stable_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 stable_sort array before sorting = 102, 425, 102, 34, 87, 34, array after sorting = 34, 34, 87, 102, 102, 425, using predicate stable_sort array after random_shuffle = 102, 102, 34, 87, 425, 34, array after sorting = 34, 34, 87, 102, 102, 425,
Privacy Policy
|
Link to Us
|
Links