我有一个节点列表,每个节点都可以分解成更多的节点。例如:
我用C++编写了上述聚合/分解/合并给定权重分解集合的代码。但是,我感觉还有很多优化可以做。比如,我正在循环遍历
是否有任何STL算法可以帮助我加速,并可能避免不必要的复制?
- Node0 = w01 * Node1 + w02 * Node2 + w03 * Node3
- Node1 = w12 * Node2 + w14 * Node4
我用C++编写了上述聚合/分解/合并给定权重分解集合的代码。但是,我感觉还有很多优化可以做。比如,我正在循环遍历
topWeights
的键,并将它们收集到topNodeNames
中,这似乎非常低效。是否有任何STL算法可以帮助我加速,并可能避免不必要的复制?
#include <string>
#include <unordered_map>
template<class T, class U> using umap = std::unordered_map<T, U>;
umap<std::string, double> getWeights(const std::string& nodeName, const umap<std::string, umap<std::string, double>>& weightTrees)
{
const auto it = weightTrees.find(nodeName);
if (it == weightTrees.end())
return umap<std::string, double>();
umap<std::string, double> topWeights = it->second;
std::vector<std::string> topNodeNames;
for (const auto& kv : topWeights)
topNodeNames.push_back(kv.first);
for (const std::string& topNodeName : topNodeNames)
{
umap<std::string, double> subWeights = getWeights(topNodeName, weightTrees);
if (subWeights.size() > 0)
{
const double topWeight = topWeights[topNodeName];
topWeights.erase(topNodeName);
for (const auto& subWeight : subWeights)
{
const auto it = topWeights.find(subWeight.first);
if (it == topWeights.end())
topWeights[subWeight.first] = topWeight * subWeight.second;
else
it->second += topWeight * subWeight.second;
}
}
}
return topWeights;
}
int main()
{
umap<std::string, umap<std::string, double>> weightTrees = {{ "Node0", {{ "Node1",0.5 },{ "Node2",0.3 },{ "Node3",0.2 }} },
{ "Node1", {{ "Node2",0.1 },{ "Node4",0.9 }} }};
umap<std::string, double> w = getWeights("Node0", weightTrees); // gives {Node2: 0.35, Node3: 0.20, Node4: 0.45}
}
NodeN
不依赖于具有K < N
的节点NodeK
吗)?编辑:是的,我在之前的问题中误解了规范。 - Max Langhof