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++ - 这等同于 std::string 吗?

c++ - 使用 Visual Studio 通过 DLL 边界传递 std::string 时出现问题

c++ - g++ -E 生成的翻译单元中以#符号开头的行是什么

c++ - 使用 c++ 标准库中的堆栈反转句子的单词

C++ 迭代映射

c++ - 为什么在 STL 映射中用作值的类需要在...中有一个默认构造函数?

c++ - 在 C++0x 中创建静态类型变体

C++、ASM 和 cout

c++ - 在 direct2D 中释放渐变画笔时可能会发生内存泄漏?