[英]Access only one element of a pair in an unordered_map in c++
I'm trying to get the same behavior as a rust tuple destructuring in C++.我试图在 C++ 中获得与 rust 元组解构相同的行为。 For example: I have an unordered_map I want to iterate over.
例如:我有一个想要迭代的 unordered_map。 However, The only data that I care about are the values, and not keys.
但是,我关心的唯一数据是值,而不是键。
Is there a way to iterate over it with a for loop without using the following syntax?有没有办法在不使用以下语法的情况下使用 for 循环对其进行迭代? (which is what I have for now)
(这是我现在所拥有的)
for (auto &pair : _map)
{
std::cout << pair.second << std::endl;
}
I would want to get something like this:我想得到这样的东西:
for (auto &value : _map)
{
std::cout << value << std::endl; // This would give me the value and not a pair with key and value.
}
Using the range-v3 library, you can iterate over keys:使用 range-v3 库,您可以遍历键:
for (auto key : m | views::keys)
// use key
or over values:或超过值:
for (auto value : m | views::values)
// use value
where m
can be a map
.其中
m
可以是map
。
In c++17, you could do:在 c++17 中,您可以执行以下操作:
for ([[maybe_unused]] auto [key, value] : m)
// use key or value
Note that the attribute [[maybe_unused]]
is used to suppress the warnings about not using one of the variables.请注意,属性
[[maybe_unused]]
用于抑制有关不使用其中一个变量的警告。
If your compiler supports the C++ 17 Standard then you can write something like the following如果您的编译器支持 C++ 17 标准,那么您可以编写如下内容
#include <iostream>
#include <unordered_map>
#include <string>
int main()
{
std::unordered_map<int, std::string> m =
{
{ 1, "first" },
{ 2, "second" }
};
for ( const auto &[key, value] : m )
{
std::cout << value << ' ';
}
std::cout << '\n';
return 0;
}
The program output is程序 output 是
second first
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.