Posted: Thu Dec 08, 2005 10:57 pm Post subject: C++ Help!
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.
When I try to debug the program, I keep getting an error. If I say no, it breaks. If I say yes to continue it executes fine. The error is:
error C2664: 'maxLoc' : cannot convert parameter 1 from 'std::list<_Ty>::iterator' to 'std::list<_Ty> &'
with
[
_Ty=std::string
]
and
[
_Ty=std::string
]
Anyone have an idea what I am doing wrong? Here is my code:
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 max = 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;
//call the maxLoc function and pass max into main()
maxLoc(max);
//Output the max element that was found
cout << "The Max Element is " << *max << endl << endl;
//erase the element found at maxLoc from teh list
cout << "Press Enter to remove " << *max << " from the list and continue." << endl << endl;
aList.erase(max);
//reset the iter and maxLoc pointers
iter = aList.begin();
max = aList.begin();
cin.get();
}//end loop
cout << "The List is Empty." << endl;
cout << "Press Enter to Continue";
cin.get();
return 0;
}//end main()
list<string>::iterator maxLoc(list<string>& aList)
{
list<string>::iterator iter = aList.begin();
list<string>::iterator max = aList.begin();
//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 > *max)
max = iter;
++iter;
return max;
}//end loop
You need to pass it a pointer to max, not the iterator itself. Your maxLoc function is expecting and address (signified by '&'), so when you call maxLoc in the main(), send it a pointer to max (*max).
So something like: maxLoc(*max)
If I read it correctly, that should fix it. _________________ White Papers
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum