c++ - 使用迭代器获取 std::list 中的下一个元素

标签 c++ stl

我正在尝试获取 std::list 中连续元素之间的差异。我尝试了以下解决方案,但作为 this线程说,我需要复制迭代器并递增它。不确定这是什么意思,因为向迭代器添加数字也会导致错误。我在这里错过了什么。我使用的是以前版本的 C++ 但不是 C++ 11

#include "stdafx.h"
#include <list>
#include <iostream>
using namespace std;

int main()
{
    std::list<int> myList;
    //for (int i = 10;i < 15;i++)
    myList.push_back(12);
    myList.push_back(15);
    myList.push_back(18);
    myList.push_back(19);
    myList.push_back(25);

    for (std::list<int>::const_iterator itr = myList.begin();itr != myList.end();++itr)
    {
        int x = *itr;
        int y = *(itr + 1);
        int diff = std::abs(x - y);
        cout << diff << "\n";
    }

    return 0;
}

最佳答案

如何使用 adjacent_difference

std::adjacent_difference(myList.begin(), myList.end(), tempList );

See Here


如果您对实现感兴趣,请查看附加链接中可能的实现部分的实现方式。您所要做的就是用列表迭代器替换,输出只显示在屏幕上,或存储它。

关于c++ - 使用迭代器获取 std::list 中的下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47048798/

相关文章:

C++ 简单指针错误无法弄清楚为什么?

c++ - 在 O(n) 中搜索 std::map 以获取部分键

c++ - 拼接和插入的区别

c++ - C++ 中的递归选择不能完全工作

c++ - nasm/yasm 参数,与 C++ 的链接

C++ Array of 120 ob​​jects with constructor + parameters, header- + sourcefile, no pointers please!

c++ - 针对 resize() + 迭代器的循环 push_back

c++ - make_pair 如何隐式推断类型?

c++ - 在哪里可以找到 STL 集合类中的 _M_key_compare 函数定义?

C++ 错误 std::result_of 没有命名类型