基于unordered_map性能的图(简短版本)
Graph based on unordered_map performance (short version)
你好:)我正在实现一些顶点是字符串的图。我用它们做了很多事情,所以使用字符串是非常无效的。这就是为什么我使用索引,简单的整数。但是,虽然其余的类工作相当快,我有麻烦的部分,我抄在下面。我在某处读到过,unordered_map需要一些哈希函数,我应该添加它吗?如果是,怎么做?下面的代码包含了我对unordered_map所做的一切。
提前感谢您的帮助:)
class Graph
{
private:
unordered_map <string, int> indexes_of_vertices;
int number_of_vertices;
int index_counter;
int get_index(string vertex)
{
if (indexes_of_vertices.count(vertex) == 0) // they key is missing yet
{
indexes_of_vertices[vertex] = index_counter;
return index_counter++;
}
else
return indexes_of_vertices[vertex];
}
public:
Graph(int number_of_vertices)
{
this->number_of_vertices = number_of_vertices;
index_counter = 0;
}
};
下面是对这个重要函数的快速优化:
int get_index(const string& vertex)
{
typedef unordered_map <string, int> map_t;
pair<map_t::iterator, bool> inserted =
indexes_of_vertices.insert(map_t::value_type(vertex, index_counter));
if (inserted.second) // the key was missing until now
return index_counter++;
else // inserted.second is false, means vertex was already there
return inserted.first->second; // this is the value
}
优化是:
- 接受const-ref参数
- 做一个单一的地图查找而不是两个:我们推测插入(),然后看看它是否工作,这节省了冗余查找在任何情况下。
请让我们知道这有多大的不同。另一个想法是,如果您的键通常很小,则使用自包含的字符串类型,如GCC的vstring,这样可以避免为少于一打或二十几个字符的字符串分配非原位内存。然后考虑您的数据是否真的足够大,可以从哈希表中获益,或者其他数据结构是否会更有效。
相关文章:
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 导入库可以跨dll版本工作吗
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 在clang++预处理器中确定gcc工具链版本
- 码头化的C++应用程序是否向后兼容早期的内核版本
- 不同的Visual Studio版本中缺少.dll
- 用符号版本替换对函数的所有调用
- luaL_dofile在已知良好的字节码上失败,可以使用未编译的版本
- 正在解码MSVC 32位版本的程序集(作业).没有手术做什么
- 我需要分发哪些版本的可再分发文件
- CV_OCL_RUN宏如何在OpenCV(版本3.4.5)的goodFeaturesToTrack实现中工作?
- 在运行时读取 libstdc++ 版本
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- Vulkan SDK 版本 1.1.85.0 在 Kubuntu 18.10 上链接
- 如何正确实现与基类不同的版本?
- 从预处理器获取 Windows 版本(C++ Win32)
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 如何在C++中将 Python 字符串转换为其转义版本?
- Qt版本应该在其他计算机上运行吗?