c++ - 优化 C++ 代码(使用 UnorderedMap 和 Vector)

标签 c++ optimization vector unordered-map

我正在尝试优化花费很长时间的 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/

相关文章:

python - 在 Python 中有效确定幂集成员之间的子集

c - C 函数示例

java - 我的 Vector 丢失数据有什么原因吗?

c++ - 将空终止的 const char* 字符串数组转换为 std::vector< std::string >

c++ - 获取应用程序图标的问题

C++错误: fields must have a constant size

c++ - 使用作为对 vector 元素的引用的参数调用 c++ 函数

c++ - 如何在 C/C++ 中捕获现有代码中的行号?

c++ - 如何优化它[C++]?

c++ - 通过修改的exp最快的pow()替换。当已经计算出较低的幂时,通过平方