我有一个小问题: 我正在使用迭代器遍历列表,但我似乎无法仅使用它访问以前的位置。
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/