如何将std :: set转换为在c ++中具有默认值的std :: map

问题描述 投票:0回答:3

我有一套钥匙。我想将这些键转换为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++ dictionary default-value
3个回答
0
投票

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

0
投票

我想添加另一种非常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);});
}


0
投票

这里是使用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++;
}
© www.soinside.com 2019 - 2024. All rights reserved.