C++11之常见标准函数练习

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.

  1. counts the elements that are equal to value.std::count()
  2. 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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值