Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector iterator not dereferencable in for loop

Tags:

c++

vector

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;
        }
    }
like image 611
TPOT94 Avatar asked Sep 05 '13 12:09

TPOT94


2 Answers

when it == v.end() - 1, you deference (it+1) so v.end(), and deference v.end() is undefined behaviour.

like image 53
Jarod42 Avatar answered Nov 15 '22 19:11

Jarod42


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;
}
like image 28
billz Avatar answered Nov 15 '22 19:11

billz