C++ groupIndex 函数优化:跳过不存在于 nodes_names 中的值
C++ groupIndex 函数优化:跳过不存在于 nodes_names 中的值
本文介绍如何优化 C++ 中的 groupIndex 函数,使之在 groups 中的每一组中的某一个值不存在于 nodes_names 中时,跳过该值,从而提高代码效率。
原始代码:
std::unordered_map<std::string, std::vector<int>> groupIndex(std::unordered_map<std::string, std::vector<std::string>> groups, std::vector<std::string> node_names)
{
std::unordered_map<std::string, int> name_to_index; // 用于存储名称到索引的映射
std::unordered_map<std::string, std::vector<int>> group_need; // 将要存储索引位置的map
// 填充名称到索引的映射
size_t size = node_names.size();
for(size_t i = 0; i < size; ++i)
{
name_to_index[node_names[i]] = i;
}
for(const auto& group : groups)
{
for(const auto& name : group.second)
{
if(name_to_index.find(name) != name_to_index.end())
{
group_need[group.first].push_back(name_to_index[name]);
}
}
}
return group_need;
}
优化后的代码:
std::unordered_map<std::string, std::vector<int>> groupIndex(std::unordered_map<std::string, std::vector<std::string>> groups, std::vector<std::string> node_names)
{
std::unordered_map<std::string, int> name_to_index; // 用于存储名称到索引的映射
std::unordered_map<std::string, std::vector<int>> group_need; // 将要存储索引位置的map
// 填充名称到索引的映射
size_t size = node_names.size();
for(size_t i = 0; i < size; ++i)
{
name_to_index[node_names[i]] = i;
}
for(const auto& group : groups)
{
for(const auto& name : group.second)
{
if(name_to_index.find(name) != name_to_index.end())
{
group_need[group.first].push_back(name_to_index[name]);
}
else
{
// 若name不存在于node_names中,则跳过这个值
continue;
}
}
}
return group_need;
}
优化思路:
在内层循环中,添加了一个判断条件 if(name_to_index.find(name) != name_to_index.end()),用来判断 name 是否存在于 node_names 中。如果不存在,则使用 continue 跳过当前循环,避免将不存在的值添加到 group_need 中。
优化效果:
优化后的代码能够有效地跳过不存在于 nodes_names 中的值,提高代码效率,尤其是在 groups 中包含大量不存在于 nodes_names 中的值的情况下,效果更加明显。
原文地址: https://www.cveoy.top/t/topic/qgWC 著作权归作者所有。请勿转载和采集!