[英]C++ Iterator access next element for comparison
我正在嘗試通過“窺視”列表中的下一個元素來比較列表中的兩個元素。 使用C ++ 11。
這可能嗎? 我有麻煩了
#include <list>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
list<int> intList;
intList.push_back(10);
intList.push_back(20);
intList.push_back(30);
intList.push_back(30);
list<int>::iterator it;
for (it = intList.begin(); it != intList.end(); it++)
{
if (*it == *it + 1)
cout << "Duplicate: " << *it << '\n';
}
}
是的,有可能:
assert(!intList.empty()); // else ++begin is UB
for (list<int>::iterator it1 = intList.begin(), it2 = ++intList.begin();
it2 != intList.end(); ++it1, ++it2)
{
if (*it1 == *it2)
cout << "Duplicate: " << *it1 << '\n';
}
可以使用std::adjacent_find()
代替(它支持std::list
迭代器)來簡化搜索:
在范圍
[first, last)
搜索兩個連續的相同元素。
例如:
list<int>::iterator it = std::adjacent_find(intList.begin(), intList.end());
if (it != intList.end())
cout << "Duplicate: " << *it << '\n';`
有可能,但是您面對的*it
增加*it
1(甚至是不同的)。
我想您的意圖是面對列表中的兩個中間元素,因此[感謝DeiDei的更正]
if ( false == intList.empty() )
{
auto it { intList.cbegin() };
auto oldVal { *it };
for ( ; ++it != intList.cend() ; oldVal = *it )
{
if ( *it == oldVal )
cout << "Duplicate: " << oldVal << '\n';
}
}
ps:對不起,我的英語不好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.