[英]C++: Error outputting a custom hash key value from unordered_map to std::cout
[英]Custom hash in std::unordered map in C++
我想满足我的C ++项目中的一些性能要求。 我发现使用push_back
到std::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.