Carrots 31 Junior Poster in Training

Hi,

I have a linked list which stores base class pointers (which point to derived type objects).

I'm trying to give this option to the user:

cout << "Press 'n' then Enter to show next, 'p' then Enter for previous and 'q' then enter to return to menu" << endl;

I tried to do it and wrote this:

case 'f':
	{
		i iter(listname.begin());
		i beginning(listname.begin());
		i end(listname.end());

		string nextPreviousChoice = "";
		do{

			cout << "Press 'n' then Enter to show next, 'p' then Enter for previous and 'q' then enter to return to menu" << endl;
			getline (cin, nextPreviousChoice);

			//FORWARDS
			if(nextPreviousChoice == "n")
			{
				if(iter == listname.end())
				{
					cout << "at end of list" << endl;
				}
				else
				{
					//++iter;//Can overun end of list and cause a crash!!!
					cout << "Name: " << (*iter)->getName() << endl; 
					//++iter;//seems not right either
				}
			}
			//BACKWARDS
			else if(nextPreviousChoice == "p")
			{
				if(iter == listname.begin())
				{
					cout << "at beginning of list" << endl;
				}
				else
				{
					--iter;
					cout << "Name: " << (*iter)->getName() << endl; 
				}
			}
			else
			{
				cout << "Tou made a invalid choice" << endl;
			}
		}
		while(nextPreviousChoice != "q");

		break;//return to main menu
	}

When a user over runs the two ends of the list, it compiles, but crashes.

The two options of forwards and backwards are not combined correctly, because I'm not able to reliably record the current position. Like when using an array you can use myarray[x].

I expect it's common for programs to need such a feature, and was hoping someone could tell me the most common and basic way to do it.

I found this code:

void print (int elem)
{
    cout << elem << ' ';
}

int main()
{
    list<int> coll;

    // insert elements from 1 to 9
    for (int i=1; i<=9; ++i) {
        coll.push_back(i);
    }

    // print all elements in normal order
    for_each (coll.begin(), coll.end(),      // range
              print);                        // operation
    cout << endl;

    // print all elements in reverse order
    for_each (coll.rbegin(), coll.rend(),    // range
              print);                        // operations
    cout << endl;
}

But this goes from the start right to the end, and then back again.

I want to be able to let the user choose whether they go forwards or backward. so I need to somehow store "current position".

Hope some one can help with this!

Been stuck for a while.

Many thanks!