Shanpei Zhou
Shanpei Zhou

Reputation: 391

iterator can not stop at the end(c++)

What I want to do is to find the kth to last element of a single linked list. I have the recursive solution below: In the main() function, I create a list holding number 10 to 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;   
}

After I created the list, I call test_func. The return value should be the iterator of the element I want.

#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;
}

The "test..." is for debugging which tells me how many times the test_func() has been called. Here, in my opinion, test_func() should be called 10 times. However, it will be call for 11 times and the last time will cause a segmentation fault.I feel like ((iter ++) != end) does not happen at the right time.

All Codes are shown below:

#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;   
}

Thanks,

Kevin Zhou

Upvotes: 0

Views: 468

Answers (1)

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11482

What you have is post increment: iter++. This means: Increment iter by one and return the old value.

What you need is pre increment: ++iter. This means: Inrement iter by one and return the new value.

Upvotes: 3

Related Questions