C++ 使用adjacent_difference

来源:互联网 发布:mysql数据库常用命令 编辑:程序博客网 时间:2024/05/29 18:48

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

#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

原创粉丝点击