The generic partial_sort algorithms with predicate : partial_sort « STL Algorithms Sorting « C++ Tutorial

Home
C++ Tutorial
1.Language Basics
2.Data Types
3.Operators statements
4.Array
5.Development
6.Exceptions
7.Function
8.Structure
9.Class
10.Operator Overloading
11.Pointer
12.File Stream
13.template
14.STL Introduction
15.string
16.vector
17.list
18.bitset
19.set multiset
20.valarray
21.queue stack
22.deque
23.map multimap
24.STL Algorithms Modifying sequence operations
25.STL Algorithms Non modifying sequence operations
26.STL Algorithms Binary search
27.STL Algorithms Sorting
28.STL Algorithms Merge
29.STL Algorithms Min Max
30.STL Algorithms Iterator
31.STL Algorithms Heap
32.STL Algorithms Helper
C / ANSI-C
C Tutorial
C++
Visual C++ .NET
C++ Tutorial » STL Algorithms Sorting » partial_sort 
27.5.4.The generic partial_sort algorithms with predicate
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;

class comp_last {
 public:
  bool operator()(int x, int yconst
    // 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;
  reverse(vector1.begin(), vector1.end());
  cout << "Before sorting:\n";
  copy(vector1.begin(), vector1.end(), out);
  cout << endl << endl;

  partial_sort(vector1.begin(), vector1.begin() 5,vector1.end(), comp_last());

  cout << "After sorting with partial_sort to get 5 values with smallest last digits:\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:
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

After sorting with partial_sort to get 5 values with smallest last digits:
10 0 11 1 12 19 18 17 16 15 9 8 7 6 5 4 14 13 3 2
27.5.partial_sort
27.5.1.Use partial_sort to sort until the first five elements are sorted
27.5.2.Use partial_sort with custom function to sort inversely until the first five elements are sorted
27.5.3.Use partial_sort to sort all elements
27.5.4.The generic partial_sort algorithms with predicate
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.