c++ - How to initialize std::map by an array?
问题描述
I have a task to fill empty std::map<char, std::set<std::string>> myMap
, by an array
const char* s[] = { "car", "sun", "surprise", "asteriks", "alpha", "apple" };
and print it using range based for
and bindings
. Result, should be like S: sun, surprise
The last one(printing) I have already implement in this way
for (const auto& [k, v] : myMap)
{
cout << "k = " << k << endl;
std::set<std::string>::iterator it;
for (it = v.begin(); it != v.end(); ++it)
{
cout << "var = " << *it << endl;
}
}
But how can I initilase this map, by const char* s[]
in right way?
P.S. I know, how to initialize it like std::map<char, std::set<std::string>> myMap = { {'a', {"abba", "abart", "audi"} } };
and I read this and this posts on StackOverflow, but I am still have no idea, how to do this by this array.
解决方案
这个怎么样?
const char* s[] = { "car", "sun", "surprise", "asteriks", "alpha", "apple" };
std::map<char, std::set<std::string>> myMap;
for (auto str : s)
myMap[str[0]].insert(str);
// Result: {
// 'a' -> {"alpha", "apple", "asteriks"},
// 'c' -> {"car"},
// 's' -> {"sun", "surprise"}
// }
推荐阅读
- python - 附加数据框的更有效方式
- python - 如何从网站上的 JavaScript 代码中抓取变量?
- sql - 如何从 Oracle DB 中传递的参数中获取表名?
- java - 变量初始化错误,但它已经是?
- typescript - 如何在 TypeScript 中转换或更改泛型类型?
- android - 如何以编程方式显示在android主屏幕上长按时打开的菜单?
- firebase - 尝试从 Dart 中的 Firestore 数据库在控制台中打印信息时出错
- gitlab - 在 Gitlab 中,文件挂钩由用户“gitlab”执行但不存在
- excel - VLOOKUP 的动态范围和标准
- django - allauth 未验证的电子邮件在电子邮件过期后仍处于未验证状态