Weird Results

Hey there, I'm working on an assignment for my comp sci class. This is the code so far:

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
31
32
33
#include <string>
#include <iostream>
#include <list>
#include "Inserter.h"
#define LIST_SIZE 5

using namespace std;

void main()
{
	try
	{
		string entry;
		list<string> myList;
		cout << "Please enter " << LIST_SIZE << " strings:" << endl;
		for (int i = 0; i < LIST_SIZE; i++)
		{
			cin >> entry;
			myList.push_front(entry);
		}

		list<string>::iterator it = myList.begin();
		cout << "Now please enter a string you would like to search for: ";
		cin >> entry;
		cout << "Your entry was found at position " << Search(myList, it, entry);
	}
	catch(string str)
	{
		cout << "Exception occured: " << str << endl;
	}

	system("pause");
}


And the header file:
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
#pragma once
#include <list>
#include <string>
#define LIST_SIZE 5
using namespace std;

int Search(list<string> & myList, list<string>::iterator & iterator, string value)
	{
		//base case, if we reach the end of the list
		if (iterator ==  myList.end())
		{
			if (*iterator == value)
				return distance(myList.begin(), iterator);
			else
				throw "The value you searched for was not found";
		}// other case, if search is correct
		else if (*iterator == value)
		{
			return distance(myList.begin(), iterator);
		}//recursively repeat the process until differnt condition is satisfied
		else
		{
			++iterator;
			Search(myList, iterator, value);
		}
	}


When you try to search for something it can actually find, it prints a very odd value (typically in the range of 1.5million) and if you try to search for something that isn't in the list, it crashes, saying usually that the iterator is not dereferencable, among other errors.

Please help me out with this, see if there's anything outstanding that requires some attention. Things like the fact that I'm using list and recursion are required by the teacher for this assignment so they're not going to change.
Yes line 12 dereferences the iterator even though it's already proven that it's invalid (== end()).

You can return a negative number (e.g. -1) instead of line 12 - 15 to show that the value can't be found. I wouldn't throw in your case.
Topic archived. No new replies allowed.