我正在尝试优化花费很长时间的 C++ 代码的某些部分(对于 X 量的数据,代码的以下部分大约需要 19 秒,我试图在不到 5 秒内完成整个过程相同数据量的秒数——基于我拥有的一些基准)。我有一个函数“添加”,我在这里编写并复制了代码。我将尝试尽可能多地解释我认为理解代码所需的内容。如果我错过了什么,请告诉我。
以下函数 add 被调用 X 次,用于 X 量的数据条目。
void HashTable::add(PointObject vector) // PointObject is a user-defined object
{
int combinedHash = hash(vector); // the function "hash" takes less than 1 second for X amount of data
// hashTableMap is an unordered_map<int, std::vector<PointObject>>
if (hashTableMap.count(combinedHash) == 0)
{
// if the hashmap does not contain the combinedHash key, then
// add the key and a new vector
std::vector<PointObject> pointVectorList;
pointVectorList.push_back(vector);
hashTableMap.insert(std::make_pair(combinedHash, pointVectorList));
}
else
{
// otherwise find the key and the corresponding vector of PointObjects and add the current PointObject to the existing vector
auto it = hashTableMap.find(combinedHash);
if (it != hashTableMap.end())
{
std::vector<PointObject> pointVectorList = it->second;
pointVectorList.push_back(vector);
it->second = pointVectorList;
}
}
}
最佳答案
你正在做很多无用的操作......如果我理解正确的话,一个简化的形式可能很简单:
void HashTable::add(const PointObject& vector) {
hashTableMap[hash(vector)].push_back(vector);
}
这是可行的,因为
- 使用
operator[]
访问的 map 将创建一个默认初始化值(如果 map 中尚未存在) - 值(
std::vector
)通过引用返回,因此您可以直接push_back
传入点到它。此std::vector
要么是新插入的,要么是以前存在的,如果键已经在映射中的话。
另请注意,根据 PointObject
的大小和其他因素,通过值而不是 const PointObject& 传递
。这是一种微优化,但需要明智地执行分析。vector
可能更有效
关于c++ - 优化 C++ 代码(使用 UnorderedMap 和 Vector),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31597012/