c++ - C++ 中 std::unordered_map 中的自定义哈希

标签 c++ boost

我想在我的 C++ 项目中满足一些性能要求。我发现对 std::vector 使用 push_back 会降低性能。此外,当我对 std::vector 的元素使用 find 时,它也比使用 unordered_map 花费更多的时间。

如果我在 unordered_map 上使用 emplace 可以吗?可以更快地完成保存/获取周期吗?

g++ driver.cpp -std=c++11

头文件是

#ifndef CUSTOM_UNOR_MAP_HPP
#define CUSTOM_UNOR_MAP_HPP


#include <boost/algorithm/string/predicate.hpp>
#include <boost/functional/hash.hpp>
#include <unordered_map>


namespace pe
{

    struct pe_hash
    {

        size_t operator()(const std::string& key) const
        {

            std::size_t seed = 0;
            std::locale locale;

            for(auto c : key)
            {
                boost::hash_combine(seed, std::toupper(c, locale));
            }

            return seed;

        }
    };



    struct pe_key_eq
    {

        bool operator()(const std::string& l, const std::string& r) const
        {
            return boost::iequals(l, r);
        }
    };

    using pe_map = std::unordered_map<std::string, std::string, pe_hash, pe_key_eq>;

}

#endif

驱动文件(main.cpp)是

#include "pemap.hpp"
#include <iostream>


template <typename T>

    inline const std::string& get_map_value(const T& container, const std::string& key)

    {

        if (container.count(key))
        {

            return container.find(key)->second;

        }

        static std::string empty;
        return empty;

    }

int main(int argc, char** argv) {


    std::string key = "key";
    std::string val = "value1";
    std::string val2 = "value2";

    pe::pe_map container;
    container.emplace(std::move(key), std::move(val));
    container.emplace(std::move(key), std::move(val2));

    std::cout << get_map_value( container, "key") << std::endl;

}

最佳答案

I want to meet some performance requirements in my C++ project.

以下是您应该执行的步骤:

  • 运行分析器
  • 确定哪些代码和数据操作花费的时间最多
  • 为您的案例考虑更好的算法和/或数据组织(容器类型是其中之一)
  • 如果现在的性能足够了,你就完成了,如果不尝试优化代码,那将花费最多的时间

仅查看普通示例中的容器不会得到好的答案。您需要优化您的程序,而不是示例。

关于c++ - C++ 中 std::unordered_map 中的自定义哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45374584/

相关文章:

c++ - 对话框背景和单选按钮透明度

c++ - 用boost序列化一个有内嵌类的类,但是只序列化wrapper中的信息

c++ - 将 std::sort 替换为 boost::sort

c++ - CMake:如何设置库的单元测试

c++ - 将 STL 容器用于 boost::interprocess::managed_shared_memory

c++ - 有没有办法在Windows下编译为Linux编写的C++代码?

c++ - 在多线程代码中使用 shared_ptr

c++ - 如果使用 'Visual Studio 2017 (v141)' 平台工具集构建应用程序,CCheckListBox 项目会在选择时重叠

c++ - 如何在 CMAKE 中为不同的文件使用不同的编译选项进行编译?

c++ - 对数字范围使用 boost