繁体   English   中英

C ++中std :: unordered map中的自定义哈希

[英]Custom hash in std::unordered map in C++

我想满足我的C ++项目中的一些性能要求。 我发现使用push_backstd::vector会降低性能。 另外,当我将find用于std::vector的元素时,也比使用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;

}

我想满足我的C ++项目中的一些性能要求。

这是您应该执行的步骤:

  • 运行分析器
  • 确定哪些代码和数据处理花费的时间最多
  • 考虑针对您的案例的更好的算法和/或数据组织(容器类型是其中之一)
  • 如果现在的性能足够,那么您完成了,如果不尝试优化代码,则需要花费大量时间

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM