繁体   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