我正在使用一个循环来计算输入单词的次数然后打印单词和输入的次数,这有效但它从不打印最后一个单词,我按字母顺序排序.在打印最后一个单词之前,它错误地说迭代器不是可解除引用的.这是我的循环代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
bil*_*llz 21
你的代码有不确定的行为-想象it指向的最后一个元素v,那么您要提领v.end()的*(it+1)
if (*it != *(it+1)
Run Code Online (Sandbox Code Playgroud)
STL迭代器,end不指向最后一个元素; end()返回一个迭代器,表示容器中元素的结尾.结束是最后一个元素背后的位置.这样的迭代器也称为过去的迭代器.
因此,begin()和end()定义包含第一个元素但不包括最后一个元素的半开放范围
--------------------------------
| | | | | | | | |
--------------------------------
/\ /\
begin() end()
Run Code Online (Sandbox Code Playgroud)
对于您要实现的目标,请查看std :: adjacent_find
auto it = std::adjacent_find(v.begin(), v.end());
if (it != v.end())
{
count ++;
}
else
{
cout << *it << " ---- " << count << endl;
}
Run Code Online (Sandbox Code Playgroud)