本文介绍了向量迭代器在 for 循环中不可解引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用循环来计算某个单词被输入的次数,然后打印该单词以及它被输入的次数,这可行,但它从不打印最后一个单词,我按字母顺序对其进行了排序.在打印最后一个单词之前,它会出错说迭代器不可解引用.这是我的循环代码:

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;
        }
    }

推荐答案

你的代码有未定义的行为 - 想象 it 指向 v 的最后一个元素,那么你正在尝试取消引用 *(it+1)

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迭代器,end不指向最后一个元素;end() 返回一个迭代器,表示容器中元素的结尾.结尾是最后一个元素后面的位置.这样的迭代器也称为过去结束迭代器.

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.

因此,begin() 和 end() 定义了一个半开范围,该范围包括第一个元素但排除最后一个

Thus, begin() and end() define a half-open range that includes the first element but excludes the last

 --------------------------------
 |  |   |   |   |   |   |   |   |
 --------------------------------
  /\                               /\
begin()                            end()

对于您想要实现的目标,请查看 std::adjacent_find

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;
}

这篇关于向量迭代器在 for 循环中不可解引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:44