Lists & Iterators

Hi. I'm a second-semester C++ student and am having quite a hard time with this assignment. The problem is:

Write a program that accepts strings from the console into a list and outputs them using iterators in alphabetical order.

Here's a snippet of the program so far. I figure that if I check if my current string (myString) is < the current position of the list (*pos), then I can .insert() myString into the list at that position. If it's not <, then the loop would just continue moving the pos iterator up until it does find a place where myString < *pos. However, this doesn't perform the insert if myString happens to be the LAST one in alphabetical order. I don't know how to continue with this 'bug'. Any help would be great.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
	list<string> myList;
	string myString;

	int i=1; //counter
	do
	{

		//ask for String
		cout << "Insert a string: ";
		//put string into myString
		cin >> myString;

		if (i==1)
			myList.push_back(myString);

		//pos points to 0 (.begin())
		for (list<string>::iterator pos = myList.begin(); pos != myList.end() && i != 1; ++pos)
		{

			if (myString < *pos)
			{
				myList.insert(pos, myString);
				break;
			} 

		}


		i++;
	} while (i<=STRINGS_TO_USE);
STL lists have a sort() method. Could you just push back each of the strings, call sort, and then use an iterator to display them?
No. We're not to use sort.
I'd make a bool function 'insert_my_sting' from lines 17 to 26.
then
if(!insert_my_string(mystring, mylist)) mylist.push_back(mystring);

also you don't need that condition (&& i != 1). you could simply add else on line 15
Last edited on
In that case, I would suggest writing your own version of sort that sorts your container or string, then just using that. Of course your sort would use iterators (which is what they are intending for you to do I guess).

EDIT: Actually, hamsterman's idea is probably better if you do it right.
Last edited on
if(!insert_my_string(mystring, mylist)) mylist.push_back(mystring);

I don't know how to interpret this. Does it read, "if insert_my_string isn't done, push_back myList"? I don't see how I could implement that at the right point to have it work right.
Topic archived. No new replies allowed.