简体   繁体   English

std::map 用键的索引遍历键

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

I need to iterate through the keys of a map, but looking ahead to future keys.我需要遍历地图的键,但展望未来的键。 For example:例如:

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
}

but sometimes I don't want to see the next element (n+1), maybe I want to see the n+10 element, etc. How do I do this?但有时我不想看到下一个元素 (n+1),也许我想看到 n+10 元素,等等。我该怎么做? If my list has 100 elements, and I arrive at element 99, then 99+10 is gonna break evrything.如果我的列表有 100 个元素,而我到达了元素 99,那么 99+10 会破坏一切。 Is there a way to test if my iterator can achieve n+10?有没有办法测试我的迭代器是否可以达到 n+10?

The best solution I thougth of is to keep track of an index i and see if I can call it + 10 (that is, if i+10<mapSize ).我认为最好的解决方案是跟踪索引i并查看是否可以将it + 10称为it + 10 (即,如果i+10<mapSize )。 Bus is there a more elegant way?公交车有没有更优雅的方式? Maybe testing if the n+10 iterator exists or something?也许测试n+10迭代器是否存在?

Map does not sound like the appropiate data type for your use case. Map 听起来不像适合您的用例的数据类型。 Try switching to a container that supports random access尝试切换到支持随机访问的容器

I think that your are looking for something like std::advance (Please see here ), but with an additional check, if the advance operation was past the end or not.我认为您正在寻找类似std::advance (请参见此处)的内容,但需要额外检查,如果提前操作是否已结束。

We can use a small lambda to do this kind of check.我们可以使用一个小的 lambda 来做这种检查。 Since it uses only an increment operation, it should work for all type of containers.由于它仅使用增量操作,因此它应该适用于所有类型的容器。

Please see the following example to illustrate the function:请参阅以下示例来说明该功能:

#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