c++ - 列表迭代器功能障碍

标签 c++ list

我有一个小问题: 我正在使用迭代器遍历列表,但我似乎无法仅使用它访问以前的位置。

std::list<int>::iterator i;
for(i=mylist.begin();i!=mylist.end();i++)
{
        if(*i<0) fprintf(fout,"%d",*(i-1));//here i want to access the (i-1)th element 
}

最佳答案

这是一种适用于 C++03 的方法:

#include <iostream>
#include <list>

int main()
{
    std::list<int> mylist { 11, -22, -33, 44, -55 };
    std::list<int>::iterator i, j;
    if (!mylist.empty())
    {
        for (i = mylist.begin(); ++i != mylist.end(); )
            if (*i < 0)
                printf("%d ",*--(j=i));
        printf("\n");
    }
}

在 C++11 中,您可以用 std::prev(i) 替换 j 的错误,正如 Columbo 首先建议的那样......

请注意,我更改了您的循环以避免在 *begin()“之前”可能尝试访问某些想象中的元素。你可以看到它正在运行 here .

关于c++ - 列表迭代器功能障碍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26862372/

相关文章:

c++ - Qt Creator中如何使用QPainter显示动态圆圈

c++ - 在 Linux 中更改 I2C 速度

c++ - 如何在带有图像背景小部件 View 的 Qt 中获取用户输入?

php - CSS 和 SQL 填充列表

python - 如何查找密码是否包含列表中的所有字符?

c++ - 自动换行 ostream

c++ - 如何从.cpp文件和makefile编译程序

jquery - 使用 jQuery 将 TM 添加到文本中?

python - 按值对 python 字典列表进行分组

list - haskell列表和功能