的問題是,你正在推進i
:
set<int>::iterator i = myset.begin(); // <-- i points to first element
set<int>::iterator j = i++; // <-- j points to first element
// i points to second!
while (1)
{ // so if our set starts with {0, 1, ...}
if (*(j) != *(i)+1) // then *j == 0, *i == 1, *i + 1 == 2, so this
// inequality holds
你的意思是什麼做的是有j
是下一個迭代後i
:
std::set<int>::iterator i = myset.begin(), j = myset.begin();
std::advance(j, 1);
用C++ 11 ,還有std::next()
:
auto i = myset.begin();
auto j = std::next(i, 1);
,或者,只是扭轉你的建築:
std::set<int>::iterator j = myset.begin();
std::set<int>::iterator i = j++; // now i is the first element, j is the second
或者,最後,你真的只需要一個迭代器:
int expected = 0;
for (std::set<int>::iterator it = myset.begin(); it != myset.end();
++it, ++expected)
{
if (*it != expected) {
std::cout << "Missing " << expected << std::endl;
break;
}
}
很好的解釋,但爲了處理缺失數字在集合末尾的情況,這是我給出的第一個示例,該如何處理? –
對於初學者來說,問題是他正在訪問超出數組的末尾。使用兩個迭代器(加上結束迭代器)編寫正確的代碼是很有可能的,儘管恕我直言,這不是最好的解決方案。但在任何情況下,您都必須確保所有對該集合的訪問都在限制範圍內。 –
換句話說,您的上一個版本是最好的方法。但爲什麼會把問題與'break'混淆?只需將條件添加到'for'中的條件中,並且當您離開循環時,無論「預期」是什麼,那就是他正在尋找的值。 –