簡體   English   中英

std::map 用鍵的索引遍歷鍵

[英]std::map iterate through keys with index of key

我需要遍歷地圖的鍵,但展望未來的鍵。 例如:

map<int, int> m;
vector<int> v;
for(map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {
  cout << it->first << "\n";
  //is the next element equal to 3?
  auto next = it++;
  std::cout << "equals 3" << next==3 << std::endl
}

但有時我不想看到下一個元素 (n+1),也許我想看到 n+10 元素,等等。我該怎么做? 如果我的列表有 100 個元素,而我到達了元素 99,那么 99+10 會破壞一切。 有沒有辦法測試我的迭代器是否可以達到 n+10?

我認為最好的解決方案是跟蹤索引i並查看是否可以將it + 10稱為it + 10 (即,如果i+10<mapSize )。 公交車有沒有更優雅的方式? 也許測試n+10迭代器是否存在?

Map 聽起來不像適合您的用例的數據類型。 嘗試切換到支持隨機訪問的容器

我認為您正在尋找類似std::advance (請參見此處)的內容,但需要額外檢查,如果提前操作是否已結束。

我們可以使用一個小的 lambda 來做這種檢查。 由於它僅使用增量操作,因此它應該適用於所有類型的容器。

請參閱以下示例來說明該功能:

#include <iostream>
#include <map>
#include <iterator>

using Type = std::map<int, int>;
using TypeIter = Type::iterator;

int main() {
    // Lambda to advance a container iterator and check, if that was possible
    auto advanceAndCheck = [](const Type& t, const TypeIter& ti, size_t advance) -> std::pair<bool, TypeIter>
        { TypeIter i{ ti }; while ((i != t.end()) && (advance--)) ++i;  return { i != t.end(), i }; };


    // Test data
    Type m{ {1,1}, {2,2}, {3,3}, {4,4}, {5,5} , {6,6} };

    // Iterate over container
    for (TypeIter it = m.begin(); it != m.end(); ++it) {

        // Show some values
        std::cout << it->first << "\n";

        // Test
        {
            // Advance and check
            auto [OK, itn] = advanceAndCheck(m, it, 1);
            if (OK && itn->first == 3) std::cout << "The next Element is 3\n";
        }
        {
            // Advance and check
            auto [OK, itn] = advanceAndCheck(m, it, 5);
            if (OK && itn->first == 6) std::cout << "The 5th next Element is 6\n";
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM