gpt4 book ai didi

c++ - 从 map> 访问元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:07:31 25 4
gpt4 key购买 nike

我正在使用如下所示的数据结构:

map<string, set<string>> data;

到目前为止,我在使用 foreach 循环处理 map 时没有遇到任何问题,但是,现在我需要像这样打印出 map 中的数据:

KEY: elem1, elem2, elem3
KEY2: elem1, elem2, elem3

由于末尾缺少逗号,我不能再使用 foreach 循环了(可以吗?)。由于我是 C++、C++11 及其提供的所有乐趣的新手,所以我很迷茫。我想到了:

for ( auto i : data )
{
cout << i.first << ": ";
for ( size_t i = 0; i < /* size of the set */ - 1; i ++ )
cout << j << ", ";

cout << /* the last element of the set */ << endl;
}

我知道自己想要什么,只是对语法一无所知,C++ 引用也帮不上什么忙。感谢您的回答,同时我将自己浏览 C++ 引用资料。

最佳答案

我经常使用的模式(使用 BOOST_FOREACH)是:

bool first = true;
for (auto const& e: collection) {
if (first) { first = false; } else { out << ", "; }
...
}

虽然有一种 STL 方法可以做到这一点,使用 ostream_iterator:

std::copy(collection.begin(), collection.end(),
std::ostream_iterator<value_type>(out, ", "));

所以你的例子变成了:

for (auto const& pair: map) {
out << pair.first << ": ";

std::copy(pair.second.begin(), pair.second.end(),
std::ostream_iterator<std::string>(out, ", "));
}

但老实说,我仍然觉得使用 bool first = true 方法更具可读性。

关于c++ - 从 map<key, set<datatype>> 访问元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22283424/

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