gpt4 book ai didi

C++ std::map> 。如何循环设定值?

转载 作者:行者123 更新时间:2023-11-28 00:08:45 28 4
gpt4 key购买 nike

我已经在 C++ 的 map 中声明了一个集合为 std::map<std::string, std::set<std::string>> .如何循环访问或打印设定值?

最佳答案

如果你知道如何迭代 std::mapstd::set单独地,您应该可以毫无问题地组合迭代它们。请注意,如果您迭代 std::map使用基于范围的 for循环,你正在迭代 std::pair<K, V> K在哪里是 key 的( const -限定)类型和 V值的类型。如果您只想迭代单个集合(与单个键相关联),只需访问该元素并正常迭代它即可。

#include <iostream>
#include <map>
#include <set>
#include <string>

int
main()
{
auto stuff = std::map<std::string, std::set<std::string>> {
{"fruits", {"apple", "banana", "orange"}},
{"vegetables", {"carrot", "cucumber"}},
{"nuts", {"peanut", "walnut", "hazelnut", "coconut"}},
};
// Iterate over a single set
for (const auto& s : stuff["fruits"])
std::cout << s << "\n";
std::cout << "\n";
// Iterate over the whole data structure
for (const auto& pair : stuff)
{
std::cout << pair.first << ":";
for (const auto& s : pair.second)
std::cout << " " << s;
std::cout << "\n";
}
}

输出:

apple
banana
orange

fruits: apple banana orange
nuts: coconut hazelnut peanut walnut
vegetables: carrot cucumber

关于C++ std::map<std::string, std::set<std::string>> 。如何循环设定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34110242/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com