18.2.3【STL常用查找算法adjacent_find、binary_search】

 1 #include<iostream>
 2 #include<cstdlib>
 3 using namespace std;
 4 #include<vector>
 5 #include<algorithm>
 6 #include<string>
 7 
 8 
 9 /*
10     5.2.3 adjacent_find
11         查找相邻重复元素
12         adjacent_find(iterator beg, iterator end);
13         // 查找相邻重复元素,返回相邻元素的第一个位置的迭代器
14         // beg 开始迭代器
15         // end 结束迭代器
16         面试题中如果出现查找相邻重复元素,记得用STL中的adjacent_find算法
17 
18     5.2.4 binary_search
19         查找指定元素是否存在
20         bool binary_search(iterator beg, iterator end, value);
21         // 查找指定的元素,查到 返回true 否则false
22         // 注意: 在无序序列中不可用
23         // beg 开始迭代器
24         // end 结束迭代器
25         // value 查找的元素
26         二分查找法查找效率很高,值得注意的是查找的容器中元素必须的有序序列
27 */
28 
29 
30 void test523()
31 {
32     vector<int> v;
33     v.push_back(1);
34     v.push_back(2);
35     v.push_back(5);
36     v.push_back(1);
37     v.push_back(2);
38     v.push_back(4);
39     v.push_back(4);
40     v.push_back(3);
41 
42     vector<int>::iterator it = adjacent_find(v.begin(), v.end());
43     if(it == v.end())
44     {
45         cout << "没找到" << endl;
46     }
47     else
48     {
49         cout << "找到了相邻重复元素为:" << *it << endl;
50     }
51 }
52 
53 
54 void test524()
55 {
56     vector<int> v;
57     for(int i=0; i<10; i++)
58     {
59         v.push_back(i+1);
60     }
61     //v必须有序,若无序则result正确性未知
62 
63     //二分查找
64     bool result = binary_search(v.begin(), v.end(), 2);
65     if(result)
66     {
67         cout << "找到了" << endl;
68     }
69     else
70     {
71         cout << "没找到" << endl;
72     }
73 }
74 
75 
76 int main()
77 {
78     test523();
79     test524();
80 
81     system("pause");
82     return 0;
83 }

 

posted @ 2021-05-13 11:49  yub4by  阅读(49)  评论(0)    收藏  举报