fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <stdio.h>
  4. #include <algorithm>
  5.  
  6.  
  7. using namespace std;
  8.  
  9. struct Point{
  10. int x;
  11. int y;
  12. };
  13.  
  14. template<class iterator,class T,class O>
  15. iterator insert_pos(iterator beg, iterator end,T val,O op) {
  16. while(beg!=end) {
  17. iterator mid = beg + (end-beg)/2 ;
  18. if(!op(*mid,val)) end = mid ;
  19. else if(beg==mid) return end ;
  20. else beg = mid ;
  21. }
  22. return end ;
  23. }
  24.  
  25.  
  26. struct compare_functor : public binary_function<bool,Point,Point>
  27. {
  28. bool operator ()(const Point &lhs, const Point &rhs) {
  29. return lhs.x<rhs.x ;
  30. }
  31. };
  32.  
  33. int main() {
  34. vector<Point> points;
  35. for (int i = 0; i<100; i++) {
  36. //ランダムな点を生成
  37. Point pt = { rand() % (i+1), 0 };
  38. auto pos=insert_pos(points.begin(),points.end(),pt,compare_functor()) ;
  39. if(pos==points.end())
  40. points.push_back(pt) ;
  41. else
  42. points.insert(pos,pt) ;
  43. }
  44.  
  45. //要素を順に表示
  46. for (int i = 0; i < 100; i++) {
  47. cout << points[i].x << endl;
  48. }
  49.  
  50. return 0;
  51.  
  52. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
0
0
0
0
0
0
0
1
1
1
1
1
2
2
2
2
2
3
3
3
3
3
4
5
5
5
6
6
7
7
7
7
7
7
8
8
8
8
9
11
11
11
12
13
14
14
14
14
15
16
16
16
17
18
18
19
19
20
20
20
21
21
21
21
22
23
23
23
24
24
25
26
26
26
27
28
32
32
34
34
36
39
39
43
47
50
51
51
52
53
62
62
63
64
67
68
70
75
93
94