R
Rishi Dhupar
Hi,
Been trying to figure out how to use iterators. Basically trying to
sort the list using iterators. Here are my functions, problem is it
doesn't seem to be sorting at all. I think it has to do with my
selectionSort adding and removing elements from the list on each for
loop.
Any suggestions on what to do.
Thanks,
RishiD
// returns an iterator pointing to the largest element in the range
[first, last)
template <typename T>
typename list<T>::iterator maxIter(typename list<T>::iterator first,
typename list<T>::iterator last)
{
list<T>::iterator tempIter = first;
list<T>::iterator max = first;
int dCounter = 0;
while (tempIter != last)
{
cout << "maxIter counter " << dCounter++ << endl;
if (*tempIter > *max)
{
//cout << "old max " << *max << " setting to " << *tempIter << endl;
max = tempIter;
}
tempIter++;
}
return max;
}
// use selection sort to order aList
template <typename T>
void selectionSort(list<T>& aList)
{
list<T>::iterator maxNumber;
list<T>::iterator passIter = aList.begin();
for (int i = 0; i < aList.size(); i++)
{
// returns iterator to the max number between passIter and
aList.end()
maxNumber = maxIter<T> (passIter, aList.end());
// store the max number, temporaryly
int temp = *maxNumber;
cout << "passIter " << *passIter << " maxNumber return " << temp <<
endl;
// remove item from aList
aList.erase(maxNumber);
// adds the value to front of aList, also implies passIter++
aList.push_front(temp);
}
}
Been trying to figure out how to use iterators. Basically trying to
sort the list using iterators. Here are my functions, problem is it
doesn't seem to be sorting at all. I think it has to do with my
selectionSort adding and removing elements from the list on each for
loop.
Any suggestions on what to do.
Thanks,
RishiD
// returns an iterator pointing to the largest element in the range
[first, last)
template <typename T>
typename list<T>::iterator maxIter(typename list<T>::iterator first,
typename list<T>::iterator last)
{
list<T>::iterator tempIter = first;
list<T>::iterator max = first;
int dCounter = 0;
while (tempIter != last)
{
cout << "maxIter counter " << dCounter++ << endl;
if (*tempIter > *max)
{
//cout << "old max " << *max << " setting to " << *tempIter << endl;
max = tempIter;
}
tempIter++;
}
return max;
}
// use selection sort to order aList
template <typename T>
void selectionSort(list<T>& aList)
{
list<T>::iterator maxNumber;
list<T>::iterator passIter = aList.begin();
for (int i = 0; i < aList.size(); i++)
{
// returns iterator to the max number between passIter and
aList.end()
maxNumber = maxIter<T> (passIter, aList.end());
// store the max number, temporaryly
int temp = *maxNumber;
cout << "passIter " << *passIter << " maxNumber return " << temp <<
endl;
// remove item from aList
aList.erase(maxNumber);
// adds the value to front of aList, also implies passIter++
aList.push_front(temp);
}
}