C++ 使用adjacent_difference

用来计算容器相邻元素的关系,除了相邻元素之差,或自定义相邻元素操作:

#include <numeric>
#include <vector>
#include <iostream>
#include <functional>

int main()
{
    // Default implementation - the difference b/w two adjacent items

    std::vector<int> v{2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
    std::adjacent_difference(v.begin(), v.end(), v.begin());

    for (auto n : v) {
        std::cout << n << ' ';
    }
    std::cout << '\n';

    // Fibonacci 
    // Notice, next item on the list is the result of the current iteration

    v = std::vector<int>(10);
    v[0] = 1;

    std::adjacent_difference(v.begin(), v.end() - 1, v.begin() + 1, std::plus<int>());

    for (auto n : v) {
        std::cout << n << ' ';
    }
    std::cout << '\n';
}

假设给一个vector<T>path,如何打印出:
a->b->c
这样的效果,如果使用迭代的方式,就需要进行if判断在最后的一个元素不输出->,看起来更简单的办法是使用adjacent_difference

template <class T>
void Print(vector<T> a)
std::adjacent_difference(a.begin(),a.end(),
    ostream_iterator<T>(std::cout),
        [](T x, T y)
            {
                cout<<"->";
                return x;});

参考:
http://en.cppreference.com/w/cpp/algorithm/adjacent_difference

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值