I have a homework assignment I am having trouble with. The instructions are:
Implement the function maxLoc(), which return an iterator pointing at the largest element in a list.
// return an iterator pointing to the largest element
// in the list.
templete <typename T>
list<T>::iterator maxLoc(list<T>& aList);
Write a program that tests maxLoc(), using the following declarations:
string strArr[] = {"insert", "erase", "templete", "list"};
int strSize = sizeof(strArr) / sizeof(string);
list<string> strList(strArr, strArr+strSize);
The program should repeatedly call maxLoc(),
output the largest value, and then delete the value, until the list is empty.
Now my program executes fine. The problem is when it gets to the line to erase the elements at maxLoc, it is erasing the first element in the list instead. I cannot figure out why it is doing this because there is nothing in there re-assigning maxLoc to the beginning of the list.
What am I doing wrong? Can I not use aList.erase(maxLoc) to erase teh element at *maxLoc? I tried useing aList.erase(iter) but that gave me sevaral errors. I just can't see how maxLoc is reassigning to the first element in the list.
Code:
#include <iostream>
#include <list>
#include <string>
#include <cstdlib>
using namespace std;
template <typename T>
list<string>::iterator maxLoc(list<string>& aList);
int main()
{
string strArr[] = {"insert","erase","template","list"};
int strSize = sizeof(strArr)/sizeof(string);
list<string> aList(strArr, strArr + strSize);
list<string>::iterator iter = aList.begin();
list<string>::iterator maxLoc=aList.begin();
//validate that the list is not empty. Run loop until aList.empty() = true
while (!aList.empty())
{
cout << "The list contains the elements " << endl;
//loop reads through the list and sets the maxLoc to equal iter if iter is greater than the current maxLoc
while (iter!=aList.end())
{
cout << *iter << endl;
if (*iter > *maxLoc)
*maxLoc = *iter;
++iter;
}//end loop
//Output the max element that was found
cout << "Max Element is " << *maxLoc << endl << endl;
//erase the element found at maxLoc from teh list
cout << "Remove " << *maxLoc << " from the list." << endl << endl;
aList.erase(maxLoc);
//reset the iter and maxLoc pointers
iter = aList.begin();
maxLoc = aList.begin();
cin.get();
}//end loop
cout << "The List is Empty." << endl;
cout << "Press Enter to Continue";
cin.get();
return 0;
}//end main()