Help with printing out indices of array!

Basically what I'm trying to do is create a search function that takes 1 parameter of type T, as the value the user is looking for in the SearchArray. I have conquered being able to write this function in my main quite easily, but my assignment requires me to implement the search function inside my SearchArray class. And then create another function inside main that calls the search function from SearchArray class.

The problem is, I keep getting crazy random 10 digit numbers instead of the subscript location or index I want to return. Any help would be appreciated!

my SearchArray class (search function at bottom):

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
34
35
36
37
38
39
40
41
42
43
44
45
46
#ifndef SEARCHARRAY_H
#define SEARCHARRAY_H


#include "SafeArray.h"
#include <iostream>


template <class T>
class SearchArray : public SafeArray<T>
{
	public:
	SearchArray(int);
	SearchArray(const SearchArray<T> &);
	int search(T);
};

template <class T>
SearchArray<T>::SearchArray(int s) : SafeArray<T>(s)
{
}

template <class T>
SearchArray<T>::SearchArray(const SearchArray<T> &org) : SafeArray<T>(org)
{
}

template <class T>
int SearchArray<T>::search(T key)
{	
	SearchArray temp(*this);

	int index;	
	for (int i = 0; i < temp.getSize(); i++)
	{
		if (temp[i] == key)
		{
			index = i;
		}
		
	}	
	return index;
	
}

#endif 


And the other search function in my main:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <class T>
void search2(SearchArray<T> & array)
{
	int x;
	T val;

	cout << "Enter a value to search: ";
	cin >> val;

	x = array.search(val);
	cout << "Key " << val << " is located at index: " << x << endl;

}




Last edited on
index is not initialized.
Topic archived. No new replies allowed.