Reputation: 21
Exercise: Write a function template that takes a pair of values that represent iterators of unknow type. Find the value that occurs most frequently in the sequence
My work:
template <typename Iterator>
typename std::iterator_traits<Iterator>::value_type
funkcija(Iterator begin, Iterator end)
{
typename std::iterator_traits<Iterator>::value_type Frequency;
typename std::iterator_traits<Iterator>::value_type frequencyTemp;
typename std::iterator_traits<Iterator>::value_type frequencyHighest = 0;
for ( Iterator tempIter = begin; tempIter != end; ++tempIter)
{
frequencyTemp = count (begin, end, *tempIter);
if (frequencyTemp > frequencyHighest)
{
frequencyHighest = frequencyTemp;
Frequency = *tempIter;
}
}
return Frequency;
}
int main()
{
std::vector<std::string> words;
words.push_back("ada");
words.push_back("dada");
words.push_back("mada");
words.push_back("ada");
words.push_back("dada");
words.push_back("ada");
words.push_back("kada");
std::vector<std::string>::iterator first = words.begin();
std::vector<std::string>::iterator last = words.end();
std::cout << "Most frequent value is " << funkcija(first,
last) << std::endl;
return 0;
}
It compiles fine, but when try to run it I got error message that
Debug Assertion Failed!
Expression: invalid null pointer.
I would appreciate if someone could tell me what I did wrong.
Upvotes: 2
Views: 183
Reputation:
Check the types of your variables: some of them are wrong.
The specific thing that's triggering the message is that you are trying to initialize the string frequencyHighest
with a null pointer, as specified by the literal 0
. (i.e. it's trying to use the constructor that takes a C-style string and copies it into the newly constructed std::string
)
When your program is crashing and you don't know what's causing it, one easy thing you can often do is simply keep removing parts of your program until it stops crashing; then you know the crash is probably related to the parts you just removed.
You can usually pin the cause down very narrowly this way -- and even if you can't, it gives you a much better sample program to post when you're asking for help.
Although as the comments said, a debugger would have made it even more plain.
Upvotes: 3