I'm using a loop to count how many times that a word was entered then print the word and how many times it was entered, which works but it never prints the last word, I have it sorted alphabetically. Before the last word is printed it errors out saying the iterator is not dereferencable. Here is my code for the loop:
for (vector<string>::iterator it = v.begin() ; it != v.end(); ++it)
{
if (*it == *(it+1))
{
count++;
}
else if (*it != *(it+1))
{
count++;
cout << *it << " ---- " << count << endl;
count=0;
}
}
when it == v.end() - 1
, you deference (it+1)
so v.end()
,
and deference v.end()
is undefined behaviour.
Your code has undefined behavior - imagine it
is pointing to the last element of v
, then you are trying to dereference v.end()
in *(it+1)
if (*it != *(it+1)
STL iterator, end doesn't point to last element; end() returns an iterator that represents the end of the elements in the container. The end is the position behind the last element. Such an iterator is also called a past-the-end iterator.
Thus, begin() and end() define a half-open range that includes the first element but excludes the last
--------------------------------
| | | | | | | | |
--------------------------------
/\ /\
begin() end()
For what you are trying to achieve, have a look at std::adjacent_find
auto it = std::adjacent_find(v.begin(), v.end());
if (it != v.end())
{
count ++;
}
else
{
cout << *it << " ---- " << count << endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With