gpt4 book ai didi

c++ - 获取 map> 的键

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:15 28 4
gpt4 key购买 nike

我怎样才能得到这样一张 map 的 key map<string,vector<string>>mymap假设mymap["index"]={"val1","val2"} ?我在这里找到了像 map<string,string> 这样的法线贴图的解决方案。但为此我不知道该怎么做。

最佳答案

您可以遍历映射中的所有值(它们是成对的)并引用它们的第一个和第二个元素以分别获取键和映射值:

#include <map>
#include <vector>
#include <string>

int main()
{
std::map<std::string, std::vector<std::string>> m;
// ...
for (auto& p : m)
{
std::string const& key = p.first;
// ...

std::vector<std::string>& value = p.second;
// ...
}
}

当然,您可以使用 std::for_each 来实现同样的效果:

#include <map>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
std::map<std::string, std::vector<std::string>> m;
// ...
std::for_each(begin(m), end(m), [] (
std::pair<std::string const, std::vector<std::string>>& p
// ^^^^^
// Mind this: the key is constant. Omitting this would
// cause the creation of a temporary for each pair
)
{
std::string const& key = p.first;
// ...

std::vector<std::string>& value = p.second;
// ...
});
}

最后,您还可以使用自己的手动 for 循环,尽管我个人认为这不那么惯用:

#include <map>
#include <vector>
#include <string>

int main()
{
std::map<std::string, std::vector<std::string>> m;
// ...
for (auto i = begin(m); i != end(m); ++i)
{
std::string const& key = i->first;
// ...

std::vector<std::string>& value = i->second;
// ...
}
}

这是上面最后一个例子在 C++03 中的样子,其中不支持通过 auto 进行类型推导:

#include <map>
#include <vector>
#include <string>

int main()
{
typedef std::map<std::string, std::vector<std::string>> my_map;
my_map m;

// ...
for (my_map::iterator i = m.begin(); i != m.end(); ++i)
{
std::string const& key = i->first;
// ...

std::vector<std::string>& value = i->second;
// ...
}
}

关于c++ - 获取 map<string,vector<string>> 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15321530/

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