[英]Check if map entry is last in a range based for?
我更喜歡以與此答案相同的方式遍歷c ++ map
:
for (auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}
為此使用基於范圍的方法,是否可以確定kv
是范圍中的最后一個元素? 如果是這樣,怎么辦?
您可以獲取地圖中的最后一個鍵並進行檢查。
const auto& lastKey = myMap.rbegin()->first;
for (auto& kv : myMap) {
if(kv.first == lastKey) {
std::cout << "The last one" << std::endl;
}
std::cout << kv.first << " has value " << kv.second << std::endl;
}
如果需要倒數第二個或類似的東西,也可以使用std::prev
( reference ):
const auto& lastKey = std::prev(myMap.end(),2)->first; // gives the 2nd last
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.