#include<iostream>
#include<cassert>
usingnamespace std;
template <class elemType>
class arrayListType
{
public:
const arrayListType<elemType>& operator=
(const arrayListType<elemType>&);
bool isEmpty() const;
bool isFull() const;
int listSize() const;
int maxListSize() const;
void print() const;
bool isItemAtEqual(int location, const elemType& item) const;
void insertAt(int location, const elemType& insertItem);
void insertEnd(const elemType& insertItem);
void removeAt(int location);
void retrieveAt(int location, elemType& retItem) const;
void replaceAt(int location, const elemType& repItem);
void clearList();
int seqSearch(const elemType& item) const;
void insert(const elemType& insertItem);
void remove(const elemType& removeItem);
arrayListType(int size = 100);
arrayListType(const arrayListType<elemType>& otherList);
//~arrayListType();
protected:
elemType *list; //array to hold the list elements
int length; //to store the length of the list
int maxSize; //to store the maximum size of the list
};
//template<class int>
arrayListType<int>::arrayListType(int size)
{
size = 100;
}
template <class elemType>
int arrayListType<elemType>::seqSearch(const elemType& item) const
{
int loc;
bool found = false;
for (loc = 0; loc < length; loc++)
if (list[loc] == item)
{
found = true;
cout << "Item found at loc: " << loc;
break;
}
if (found)
return loc;
elsereturn -1;
cout << "Item not found" << endl;
} //end seqSearch
template<class elemType>
void arrayListType<elemType>::insert(const elemType &insertItem)
{
int loc;
if(length == 0) //the list is empty
list[length++] = insertItem; //insert the item and
//increment the length
elseif(length == maxSize)
cerr<<"Cannot insert in a full list,"<<endl;
else
{
loc = seqSearch(insertItem);
if(loc == -1) //the item to be inserted
//does not exist in the list
list[length++] = insertItem;
else
cerr<<"The item to be inseted is already in "
<<"the list. No duplicates are allowed."<<endl;
}
}// end insert
template<class elemType>
void arrayListType<elemType>::print() const
{
for (int i = 0; i < length; i++)
cout << list[i] << " ";
cout << endl;
}
int main()
{
arrayListType<int> myList;
myList.insert(56);
myList.insert(111);
myList.insert(54);
myList.insert(1732);
myList.print();
myList.seqSearch(54);
}
The item is in the list. I get correct results:
1 2 3
C:\Dev-Cpp\Chapter9>seqsearch
56 111 54 1732
Item found at loc: 2
If the item is not in the list. I get wrong results:
I would actually recommend removing the else statement altogether.
1 2 3 4 5 6 7
...
if (found)
return loc;
cout << "Item not found" << endl;
return -1;
...
[codetemplate <class elemType>
int arrayListType<elemType>::seqSearch(const elemType& item) const
{
int loc;
bool found = false;
for (loc = 0; loc < length; loc++)
if (list[loc] == item)][/code]
By the way what happens if your template class "elemType" is a non-numeric type for example a C-string (arrayListType<char*>)?