[英]How to convert std::set to std::map with a default value in c++
I have a Set of keys.我有一套钥匙。 I want to convert these keys into the key values of a Map.
我想将这些键转换为 Map 的键值。 I conveniently want to set each of the matching values in the Map to the same value (1).
我很方便地想将 Map 中的每个匹配值设置为相同的值 (1)。
Here is a reproducible example.这是一个可重现的示例。
set<string> keys;
keys.insert("key1");
keys.insert("key2");
map<string,int> keys_with_values;
// I want keys_with_values to equal
"key1": 1, "key2": 1
Do I have to loop through the set and insert into the map?我是否必须遍历集合并插入到地图中? If so, what is the best way to do this?
如果是这样,最好的方法是什么?
Thank you, @Sam Varshavchik --here is how I implemented the loop谢谢@Sam Varshavchik——这是我实现循环的方式
set<string> keys;
keys.insert("key1");
keys.insert("key2");
map<string,int> keys_with_values;
for(auto key : keys) {
keys_with_values[key] = 1;
}
cout << keys_with_values["key1"]; // 1
I want to add a further, very c++-y way for doing that:我想进一步添加一种非常 c++-y 的方式来做到这一点:
#include <set>
#include <map>
#include <iterator>
#include <string>
#include <algorithm>
int main () {
std::set<std::string> keys;
keys.insert("key1");
keys.insert("key2");
std::map<std::string,int> keys_with_values;
std::transform(keys.cbegin(), keys.cend(), std::inserter(keys_with_values, begin(keys_with_values)), [] (const std::string &arg) { return std::make_pair(arg, 1);});
}
Here's another way using lambdas:这是使用 lambda 的另一种方法:
for_each(keys.begin(), keys.end(), [&](auto key)
{
keys_with_values.insert({ key, 1});
});
And for completeness sake, here's one using iterators:为了完整起见,这里有一个使用迭代器:
set<string>::iterator it = keys.begin();
while (it != keys.end())
{
keys_with_values.insert({ *it, 1});
it++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.