https://en.cppreference.com/w/cpp/algorithm
std::advance()
这个函数是用来迭代器增加步距的。
std::list<int> data{1,2,3,5,8,7,};
auto it = data.begin();
std::advance(it,2);
相当于it挪到了3的位置
跟std::advance()类似的还有std::next()
但是两者区别是std::next(),使用的是返回值,原来的it不变
auto it = input.begin();
//it不变,使用返回值
auto itnext=std::next(it, 1);
std::distance()
这个一般用来计算两个迭代器步距的。
std::list<int> data{15, 7, 3, 4, 1, 9, 2, 8, 10, 6};
auto count1 = std::distance(data.begin(), data.end());
std::cout << "count=" << count1 << std::endl;
结果:10
std::count()
std::count_if()
Returns the number of elements in the range [first, last) satisfying specific criteria.
- counts the elements that are equal to value.std::count()
- counts elements for which predicate p returns true.std::count_if()
std::list<int> data{15, 7, 3, 4, 1, 9, 2, 8, 1, 10, 6};
auto n = std::count(data.begin(), data.end(), 1);
std::cout << "n=" << n << std::endl;
结果:count=2
如果想用某个表达式,则用count_if()
auto m =
std::count_if(data.begin(), data.end(), [](int i) { return i >= 10; });
std::cout << "m=" << m << std::endl;
// A simplified version of `distance` with O(N) complexity:
auto distance = [](auto first, auto last) {
return std::count_if(first, last, [](auto){return true;});
};
static_assert(distance(v.begin(), v.end()) == 10);
std::partion()
这个算法比较奇特,这里有参考:
https://blog.csdn.net/u014023993/article/details/47657967
std::list<int> input{15, 7, 3, 4, 1, 9, 2, 8, 10, 6};
std::list<T> result;
auto it = input.begin();
//相当于迭代器增加1
std::advance(it, 1);
//从input中取出it元素放在result的begin处,并且将it从input中删除
result.splice(result.begin(), input, it);
T const &pivot = *result.begin();
//从第一个元素开始,如果条件为假就停止,然后从最后一个元素开始,如果条件为真就停止,然后交换两个元素,然后
//头++,尾巴--继续进行下一步
auto divide_point = std::partition(input.begin(), input.end(),[&](T const &t) { return t < pivot; });
std::for_each()
std::array<int, 10> b = {11, 2, 31, 4, 5, 61, 7, 85};
std::for_each(std::begin(b), std::end(b),
[](const int &n) { std::cout << n << std::endl; });
std::copy()
std::forward_list()
std::find_if_not()
std::begin()
std::end()
std::size() c++17
std::iter_swap()
std::forward()