所以你有一個集合,你想看看它中的任何項目是否通過測試。做如有遍測試是容易的,會是這個樣子:有沒有真正乾淨的方法來做'如果沒有收藏'測試?
for (int i = 0; i < collectionSize; i++)
{
if(ItemPasses(collection[i]))
{
// do code for if any pass
break;
}
}
,但做相反,如果沒有通過考試,我想不出一個真正整潔的方式做到這一點,這裏有方法我能想出:
// nice to look at but uses an unecessary variable 'anItemPassed'
bool anItemPassed = false;
for (int i = 0; i < collectionSize; i++)
{
if(ItemPasses(collection[i]))
{
anItemPassed = true;
break;
}
}
if (!anItemPassed)
{
//...
}
//---------------------------------------------------------------------------------
// as efficient as possible but uses gotos.. nobody likes gotos.. lable stuff really isnt that neat.
for (int i = 0; i < collectionSize; i++)
{
if (ItemPasses(collection[i]))
{
goto ItemPassed;
}
}
//...
ItemPassed: { }
//-------------------------------------------------------------------------
// as efficient as possible and doesnt use the rarely used (and usually poorly supported in IDEs) goto/lable stuff, but doesnt use any nice loop construct, does it all manually
int i = 0;
for (; ;)
{
if (i >= collectionSize)
{
//...
break;
}
if (ItemPasses(collection[i]))
{
break;
}
i++;
}
我真的不喜歡任何這些,我一直在想,爲什麼從來就沒有一個類似的構建:
for (int i = 0; i < collectionSize; i++)
{
if (ItemPasses(collection[i]))
{
break;
}
}
finally //executed if the loop terminates normally, not via breaks.
{
//...
}
所以在短期我的問題是:有沒有真的很乾淨的做'如果沒有在c ollection'測試?如果沒有,是否有一個原因爲什麼上述不會是一個很好的語言功能?
編輯: 我立即後悔將C++放入標籤。我知道有很好的功能可以做到這一點,但假設boost庫或其他類型的文件也是用c/C++編寫的,可能他們遇到了同樣的問題。即使這些功能是建立在語言的基礎上,說'只是調用這個函數'並不是我在這種情況下尋找的答案。
所以也許我會專注於我的問題的最後一部分:是否有一個原因,爲什麼上述不會是一個很好的語言功能? 在我看來,沒有它會像'沒有'關鍵字去'如果'
這取決於數據結構。 – Rapptz
對於C++,[有一些很好的功能](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of)。 –
「無法通過」僅僅是「任何經過」的結果的否定 –