C++/STL Algorithms Sorting/stable sort

Материал из C\C++ эксперт
Версия от 13:27, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

The generic stable_sort algorithms with predicate

<source lang="cpp">

  1. include <vector>
  2. include <algorithm>
  3. include <iostream>
  4. include <iterator>

using namespace std; class comp_last {

public:
 bool operator()(int x, int y) const
   // Compare x and y based on their last base-10 digits:
 {
   return x  10;
 }

}; int main() {

 const int N = 20;
 vector<int> vector0;
 for (int i = 0; i < N; ++i)
  vector0.push_back(i);
 vector<int> vector1 = vector0;
 ostream_iterator<int> out(cout, " ");
 cout << "Before sorting:\n";
 copy(vector1.begin(), vector1.end(), out);
 cout << endl;
 sort(vector1.begin(), vector1.end(), comp_last());

 cout << "After sorting by last digits with sort:\n";
 copy(vector1.begin(), vector1.end(), out);
 cout << endl << endl;
 vector1 = vector0;
 cout << "Before sorting:\n";
 copy(vector1.begin(), vector1.end(), out);
 cout << endl;
 stable_sort(vector1.begin(), vector1.end(), comp_last());

 cout << "After sorting by last digits with stable_sort:\n";
 copy(vector1.begin(), vector1.end(), out);
 cout << endl << endl;
 return 0;

} /* Before sorting: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 After sorting by last digits with sort: 10 0 11 1 12 2 13 3 4 14 5 15 6 16 7 17 8 18 9 19 Before sorting: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 After sorting by last digits with stable_sort: 0 10 1 11 2 12 3 13 4 14 5 15 6 16 7 17 8 18 9 19

*/        
 </source>