【问题标题】:iterator can not stop at the end(c++)迭代器不能在末尾停止(c++)
【发布时间】:2014-02-25 18:52:42
【问题描述】:

我想要做的是找到单个链表的第 k 个到最后一个元素。我有下面的递归解决方案: 在 main() 函数中,我创建了一个包含数字 10 到 1 的列表

int main()
{
int i;
forward_list<int> flist;
for (i = 1; i <= 10; i ++)
    flist.push_front(i);

forward_list<int>::iterator iter;
cout << "Original Sequence:" << endl;
for (iter = flist.begin(); iter != flist.end(); iter ++)
    cout << *iter << " ";
cout << endl;

forward_list<int>::iterator end = flist.end();
forward_list<int>::iterator begin = flist.begin();
forward_list<int>::iterator ret;

ret = test_func(begin, end);
cout << "The " << TARGET << "th(st,nd,rd) to last element is " << *ret << endl;
return 0;   
}

创建列表后,我调用 test_func。返回值应该是我想要的元素的迭代器。

#define TARGET 3
static int counttt = 0;

forward_list<int>::iterator test_func(forward_list<int>::iterator iter, forward_list<int>::iterator end)
{

cout << "test..." << endl;

forward_list<int>::iterator temp;
if ((iter ++) != end)
    temp = test_func(iter, end);
counttt ++;
if (counttt < TARGET)
    return end;
else if (counttt == TARGET)
    return iter;
else
    return temp;
}

“test...”用于调试,它告诉我 test_func() 被调用了多少次。在这里,我认为 test_func() 应该被调用 10 次。但是,它会被调用 11 次,最后一次会导致分段错误。我觉得 ((iter ++) != end) 没有发生在正确的时间。

所有代码如下:

#include <forward_list>
#include <iostream>
#include <algorithm>
#include <stdlib.h>

using namespace std;

#define TARGET 3
static int counttt = 0;

forward_list<int>::iterator test_func(forward_list<int>::iterator iter, forward_list<int>::iterator end)
{

cout << "test..." << endl;

forward_list<int>::iterator temp;
if ((iter ++) != end)
    temp = test_func(iter, end);
counttt ++;
if (counttt < TARGET)
    return end;
else if (counttt == TARGET)
    return iter;
else
    return temp;
}

int main()
{
int i;
forward_list<int> flist;
for (i = 1; i <= 10; i ++)
    flist.push_front(i);

forward_list<int>::iterator iter;
cout << "Original Sequence:" << endl;
for (iter = flist.begin(); iter != flist.end(); iter ++)
    cout << *iter << " ";
cout << endl;

forward_list<int>::iterator end = flist.end();
forward_list<int>::iterator begin = flist.begin();
forward_list<int>::iterator ret;

ret = test_func(begin, end);
cout << "The " << TARGET << "th(st,nd,rd) to last element is " << *ret << endl;
return 0;   
}

谢谢,

周凯文

【问题讨论】:

    标签: c++ iterator forward-list


    【解决方案1】:

    您所拥有的是后增量:iter++。这意味着:将 iter 加一并返回 old 值。

    您需要的是预增量:++iter。这意味着:将 iter 加一并返回 new 值。

    【讨论】:

    • 非常感谢!!!我还有一个问题。此示例仅将 forward_list 作为参数。我可以让它更通用吗?列表中的数据可能是其他一些我前面不知道的数据结构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    相关资源
    最近更新 更多