持续更新中
1. count_if
//找有多少个满足lambda 的元素
//调用方式:count_if(iterator, iterator, lambda);
vector<int> a = {0, 2, 3, 4};
cout << count_if(a.begin(), a.end(), [](int a1)->bool{return a1 <= 2;});
//输出:2
2. count
//找有多少个等于val 的元素
//调用方式:count(iterator, iterator, val);
vector<int> a = {0, 2, 3, 4};
cout << count(a.begin(), a.end(), 2);
//输出:1
3.find
//找到第一个值为 val 的迭代器
//调用方式:find(iterator, iterator, val);
vector<int> a = {0, 1, 0, 2, 1};
int p = find(a.begin(), a.end(), 1) - a.begin(); //第一个值为 1的下标
int rp = a.rend() - find(a.rbegin(), a.rend(), 1) - 1;//最后一个值为 1 的下标
cout << "p = " << p << " rp = " << rp << '\n';
//输出:p = 1 rp = 4
4.find_if
//找到第一个满足lambda 的迭代器
//调用方式:find_if(iterator, iterator, lambda);
vector<int> a = {0, 10, 20, 11, 10};
int p = find_if(a.begin(), a.end(), [](int i){return i > 10;}) - a.begin();//找第一个值大于10的下标
int rp = a.rend() - find_if(a.rbegin(), a.rend(), [](int i){return i > 10;}) - 1;//找最后一个值大于10的下标
cout << "p = " << p << " rp = " << rp << '\n';
//输出:p = 2 rp = 3
5.rotate
rotate(L, M, R);
简单解释一下, rotate函数里面要放3个迭代器,L,M,R,原本数组会按照$[L, M) + [M, R)$ 的方式排列,函数操作之后,数组会按照$[M, R) + [L, M) $的方式排列
//旋转数组
//调用方式:rotate(iterator, iterator, iterator);
#define debugvec(a) cout<<#a<<": "; for(int i = 0; i < a.size(); i++) cout << a[i] << ' '; cout << endl;
vector<int> b = {2, 4, 6, 8, 10};
for(int i = 0; i < b.size(); i++){
auto a = b;// a 赋值为 b
rotate(a.begin(), a.begin() + i, a.end());
debugvec(a);//输出 a
}
cout << '\n';
for(int i = 0; i < 4; i++){
auto a = b;// a 赋值为 b
rotate(a.begin(), a.begin() + i, a.begin() + 4);
debugvec(a);//输出 a
}
函数输出
a: 2 4 6 8 10
a: 4 6 8 10 2
a: 6 8 10 2 4
a: 8 10 2 4 6
a: 10 2 4 6 8
a: 2 4 6 8 10
a: 4 6 8 2 10
a: 6 8 2 4 10
a: 8 2 4 6 10
6.unique
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
// a vector containing several duplicate elements
std::vector<int> v{1,2,1,1,3,3,3,4,5,4};
auto print = [&] (int id) {
std::cout << "@" << id << ": ";
for (int i : v)
std::cout << i << ' ';
std::cout << '\n';
};
print(1);
// remove consecutive (adjacent) duplicates
auto last = std::unique(v.begin(), v.end());
// v now holds {1 2 1 3 4 5 4 x x x}, where 'x' is indeterminate
v.erase(last, v.end());
print(2);
// sort followed by unique, to remove all duplicates
std::sort(v.begin(), v.end()); // {1 1 2 3 4 4 5}
print(3);
last = std::unique(v.begin(), v.end());
// v now holds {1 2 3 4 5 x x}, where 'x' is indeterminate
v.erase(last, v.end());
print(4);
}
7.accumulate
vector<int> a = {0, 2, 3};
int sum = accumulate(a.begin(), a.end(), 0LL);
cout << sum << '\n';
//输出:5
这是在干嘛呢