-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP6.cpp
More file actions
120 lines (98 loc) · 2.05 KB
/
P6.cpp
File metadata and controls
120 lines (98 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
* =====================================================================================
*
* Filename: P6.cpp
*
* Description:
*
* Version: 1.0
* Created: 2016年03月30日 10时02分34秒
* Last Modified: 2016年03月30日 10时02分34秒
* Revision: none
* Compiler: gcc
*
* Author: zt (),
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
/* P6 -2 */
template<typename T2>
int Count ( T2& a )
{
return ( sizeof ( a ) / sizeof ( a[0] ) ) ;
}
/* P6-3 */
template<typename T3>
void Fill ( T3* a, int start, int end, T3 value )
{
for ( int i = start; i < end; ++i )
a[i] = value;
}
/* P6-6 */
template<typename T6>
bool IsSorted ( T6& a )
{
int cnt = Count ( a );
if ( cnt < 3 )
return true;
if ( a[0] < a[cnt - 1 ] )
{
for ( int i = 0; i < cnt - 1; ++i )
{
if ( a[i] > a[i + 1] )
return false;
}
return true;
}
else
{
for ( int i = 0; i < cnt - 1; ++i )
{
if ( a[i] < a[i + 1] )
return false;
}
return true;
}
return false;
}
/* 使用std的临近查找算法,及lambda函数表达式 */
template<typename T62>
bool IsSorted2 ( std::vector<T62> a )
{
int cnt = a.size();
if ( a.front() <= a.back() )
{
auto iter = std::adjacent_find ( a.begin(), a.end(),
[] ( T62 lhs, T62 rhs )
{
return lhs > rhs;
} );
return ( iter == a.end() );
}
else
{
auto iter = std::adjacent_find ( a.begin(), a.end(),
[] ( T62 lhs, T62 rhs )
{
return lhs < rhs;
} );
return ( iter == a.end() );
}
return false;
}
char a[] = { 1, 2, 3, 4, 5};
int b[] = { 1, 2, 7, 4, 5, 6};
int c[] = { 5, 1, 3 };
std::vector<int> d = { 1, 1, 2, 3, 4, 5, 6, 7, 7};
int main ( int argc, char* argv[] )
{
if ( IsSorted2 ( d ) )
printf ( "yes\n" );
else
printf ( "no\n" );
return 0;
}