1. 查找最大最小值

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
// min_element/max_element example
#include <iostream> // std::cout
#include <algorithm> // std::min_element, std::max_element

bool myfn(int i, int j) { return i<j; }

struct myclass {
bool operator() (int i,int j) { return i<j; }
} myobj;

int main () {
int myints[] = {3,7,2,5,6,4,9};

// using default comparison:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7) << '\n';

// using function myfn as comp:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7,myfn) << '\n';

// using object myobj as comp:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7,myobj) << '\n';

return 0;
}

2. 查找

二分查找

lower_bound(起始地址, 末尾地址, target):查找第一个大于等于target目标值的位置
upper_bound(起始地址, 末尾地址, target):查找第一个大于target目标值的位置
binary_search(起始地址, 末尾地址, target):查找target是否存在于数组或vector中,找到返回true,否则返回false
这三种方法都是采用的二分查找实现的函数,用于有序数组或vector等,查找效率较高,实际写题时,直接用能较少很多代码量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector

int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20

std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30

std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20); // ^
up= std::upper_bound (v.begin(), v.end(), 20); // ^

std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';

return 0;
}

find查找

set.find(a):查找a是否在set中,如果找不到,返回set.end()
set.count(a):本来是计算a出现的次数,但是由于集合中是没有重复元素的,于是count函数也就被作为查找函数了,因为a只能出现1次或者0次,查找成功,返回1;查找失败返回0.
map.find():主要用于查找key是否存在map中,不存在返回map.end(),用法和set一样

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<bits/stdc++.h>

using namespace std;

int main(){
vector<int> v = {1,2,3,4};
set<int> s(v.begin(), v.end());
//查找2
if (s.find(2) != s.end()) cout << "查找成功" << endl;
else cout << "查找失败" << endl;
return 0;
}

swap()交换

1
2
3
4
template <class T> void swap ( T& a, T& b )
{
T c(a); a=b; b=c;
}

reverse()倒转

reverse函数反转[first, last)区间的数据,first和last都是迭代器。

1
2
3
4
5
6
7
8
template <class BidirectionalIterator>
void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
while ((first!=last)&&(first!=--last)) {
std::iter_swap (first,last);
++first;
}
}