我正在尝试解决此问题声明。
它基本上希望您将给定向量中的重复项更改为唯一形式:
例如:["name","name","name1"]
-> ["name","name2","name1"]
...您明白了
所以我想到了使用std::map
创建一个dictionary
(我也可以在这里使用unordered_map)
这就是我使用地图的方式:
std::vector<std::string> getFolderNames(std::vector<std::string>& names) {
std::vector<std::string> vec_list_of_folders;
std::map<std::string, int> map_of_names;
for (const auto& name : names) {
if (map_of_names.find(std::string(name)) == map_of_names.end()) {
map_of_names.insert(std::make_pair(name, 1));
}
else {
map_of_names[name] += 1;
}
}
puts("");
return vec_list_of_folders;
}
该函数仍处于调试模式(这说明了为什么其中一半内容未编码的原因)
我认为重要的部分是:
for (const auto& name : names) {
if (map_of_names.find(std::string(name)) == map_of_names.end()) {
map_of_names.insert(std::make_pair(name, 1));
}
else {
map_of_names[name] += 1;
}
}
我想知道是否有简单的方法可以做到这一点。类似于python中的以下代码:
file_names = ["file1", "file2", "file3", "file1"]
print(*file_names)
example_dict = dict()
for file_name in file_names:
example_dict[file_name] = example_dict.get(file_name, 0) + 1 # this is the function I'm searching an equivalent for
print(example_dict)
我该怎么办?
您的重要零件代码等效于:
for (const auto& name : names) {
map_of_names[name] += 1;
}
如果name
未找到,则值类型为默认构造,默认构造的int为0。
您可以使用defaultdict在Python中执行类似的操作:
import collections
file_names = ["file1", "file2", "file3", "file1"]
print(*file_names)
example_dict = collections.defaultdict(int)
for file_name in file_names:
example_dict[file_name] += 1
print(example_dict)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句