如何在 c++ 中使用默认值将 std::set 转换为 std::map



我有一组键。我想将这些键转换为 Map 的键值。我方便地想将地图中的每个匹配值设置为相同的值 (1(。

这是一个可重现的示例。

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 

我是否必须遍历集合并插入到地图中?如果是这样,最好的方法是什么?

我想添加一种更进一步的,非常 c++ 的方法来实现这一点:

#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);});
}

谢谢你,@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

这是使用 lambda 的另一种方法:

for_each(keys.begin(), keys.end(), [&](auto key)
{
keys_with_values.insert({ key, 1});
});

为了完整起见,这里有一个使用迭代器:

set<string>::iterator it = keys.begin();
while (it != keys.end())
{
keys_with_values.insert({ *it, 1});
it++;
}

最新更新