Hello again...
I have a different list issue this time. My program generates 20 random numbers that range from 0 to 4 and outputs them to the screen. It then uses push_back to put each number in a list.
After this, I loop through my count function and count how many times each number appears in the list and output this to the screen.
For this problem, the book requires that I use their author-created function called seqSearch (that I will provide as well). Its arguments are the <listname>.begin(), <listname>.end, and whatever we're searching for in the list. The problem I am running into is that I can get it to go and issue the seqSearch once for each number and give me a count of 1 for each numeral, but I can't seem to devise a good loop to get it to count all instances of a number in the list.
Here's my code:
Code:
#include <iostream>
#include <list>
#include <string>
#include "d_util.h" // included for the writeList function
#include "d_random.h" // for random number generation
#include "d_search.h" // for seqSearch
template <typename T>
int count(const list<T>& aList, const T& item);
int main()
{
int numList[20];
int i,j;
randomNumber rnd;
list<int> intList(numList, numList+20);
std::cout << "Here are the random numbers: " << endl;
for (i=0;i<20;i++)
{
numList[i]=rnd.random(5);
std::cout<< numList[i] << endl;
intList.push_back(numList[i]);
}
for (j=0;j<5;j++)
{
std::cout << "Here's the count of " << j << ": " << count(intList,j) << endl;
}
return 0;
}
template<typename T>
int count(const list<T>& aList, const T& item)
{
list<T> newList;
newList=aList;
int matchCount=0;
list<T>::iterator iter;
iter=seqSearch<T> (newList.begin(), newList.end(), item);
if (iter!=newList.end())
{
matchCount++;
iter=seqSearch<T> (newList.begin(), newList.end(), item);
}
return matchCount;
}
Here's the author provided function called seqSearch:
Code:
template <typename T>
list<T>::iterator seqSearch(list<T>::iterator first,
list<T>::iterator last, const T& target);
template <typename T>
list<T>::iterator seqSearch(list<T>::iterator first,
list<T>::iterator last, const T& target)
{
// start at location first
list<T>::iterator iter = first;
// compare list elements with item until either
// we arrive at last or locate item
while(iter != last && !(*iter == target))
iter++;
// iter either points at item or is last
return iter;
}
Any guidance that anyone could give would be great!
Thanks!