简体   繁体   English

遍历 C++ 17 中的映射键

[英]Iterating through map keys in C++ 17

I am looking for a way to iterate through the keys of a map in C++ 17. The way that I have in mind right now is based on the answer of thisquestion , the way is presented below.我正在寻找一种在 C++ 17 中遍历映射键的方法。我现在想到的方法是基于这个问题的答案,方法如下所示。

for (auto const& [i, val] : myMap)
...

However, I do not need to use the value val , I just need the value i .但是,我不需要使用值val ,我只需要值i Therefore, the piece of code ... does not contain any call to the value val .因此,这段代码...不包含对值val任何调用。 Consequently, whenever I compile the code, the following warning message appears:因此,每当我编译代码时,都会出现以下警告消息:

warning: unused variable ‘val’ [-Wunused-variable]
         for (auto const& [i, val] : myMap){
                                  ^

What I want is to find a way to iterate through (only) the keys of the map, ignoring the values.我想要的是找到一种方法来遍历(仅)地图的键,而忽略这些值。 Does anyone have any idea how to do it?有谁知道该怎么做?

Two options:两种选择:

  1. A ranged-for version of @πάνταῥεῖ 's answer : @πάνταῥεῖ答案的范围版本:

     for (auto const& pair : myMap) { auto key = pair.first; // etc. etc. }
  2. Use the ranges-v3 library (or std::ranges in C++20) to adapt the range myMap.begin() and myMap.end() by projecting it onto its first coordinate.使用range-v3 库(或 C++20 中的std::ranges )通过将范围投影到其第一个坐标来调整范围myMap.begin()myMap.end() Then you'd write something like:然后你会写这样的东西:

     for (auto key : keys_of(myMap) ) { // etc. etc. }

    you can do this without ranges if keys_of() materializes all of the keys, but that could be expensive for a larger map.如果keys_of()实现了所有键,则可以在没有范围的情况下执行此操作,但这对于更大的地图来说可能会很昂贵。

    (If you have weird, heavy keys, then const auto& key instead of auto key .) (如果你有奇怪的重键,那么const auto& key而不是auto key 。)

Does anyone have any idea how to do it?有谁知道该怎么做?

Sure!当然! You can just use a traditional for loop with an iterator:您可以只使用带有迭代器的传统for循环:

for(auto it = myMap.begin(); it != myMap.end(); ++it) {
    auto i = it->first;
    // ...
}

How about using Go -like unused variable declaration with _ :如何使用带有_类似Go的未使用变量声明:

for(auto const& [i, _] : myMap)
...

You can avoid the unused warnings by casting to void :您可以通过强制转换为void来避免未使用的警告:

for (auto const& [key, val] : m) {
  (void)val;  // To avoid unused warnings

  // use key
}

for(auto const & pair : myMap) since map internally stored element in std::pair format, hence you can access the element by writing, pair.first; for(auto const & pair : myMap) 因为映射内部以 std::pair 格式存储元素,因此您可以通过写入 pair.first; 来访问元素。 for key or pair.second;用于 key 或 pair.second; for value.为价值。

for (auto& [key, std::ignore] : m) {
  // use key
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM