gpt4 book ai didi

c++ - 优化 map : forwarding the key 上的初始化

转载 作者:行者123 更新时间:2023-11-28 07:17:32 26 4
gpt4 key购买 nike

我有一个应该很有趣的问题。我想在构建时“转发初始化std::unordered_map 中的项目。

这些是细节。我有一个从 std::string 到自定义类 prop 的 HashMap ,在我的梦想中,它会初始化一个成员变量来计算字符串的哈希 传递给 std::unordered_map::operator[]

这是我编写的一个方便的代码,但我不知道从哪里开始。

为什么这么麻烦?因为我想避免类似“如果字符串不在容器中计算散列;使用 prop”之类的事情。避免这种 if 可能会影响我的表现。因此,本地图在容器中添加新项目时,构造函数以及散列将仅执行一次。那就太好了。

有什么提示吗?

谢谢和干杯!

#include <iostream>
#include <string>
#include <unordered_map>

class prop
{
public:
prop(std::string s = "") : s_(s), hash_(std::hash<std::string>()(s))
{
// Automagically forwarding the string in the unordered_map...
};

std::string s_;
std::size_t hash_;
int x;
};

int main(int argc, const char * argv[])
{
// Forward the std::string to the prop constructor... but how?
std::unordered_map<std::string, prop> map;

map["ABC"].x = 1;
map["DEF"].x = 2;
map["GHI"].x = 3;
map["GHI"].x = 9; // This should not call the constructor: the hash is there already

std::cout << map["ABC"].x << " : " << map["ABC"].s_ << " : " << map["ABC"].hash_ << std::endl;
std::cout << map["DEF"].x << " : " << map["DEF"].s_ << " : " << map["DEF"].hash_ << std::endl;
std::cout << map["GHI"].x << " : " << map["GHI"].s_ << " : " << map["GHI"].hash_ << std::endl;

std::cout << map["XXX"].x << " : " << map["XXX"].s_ << " : " << map["XXX"].hash_ << std::endl;

return 0;
}

最佳答案

只需使用您的 Prop 类作为键,而不是字符串:

#include <iostream>
#include <string>
#include <unordered_map>

class prop
{
public:
prop(std::string s = "") : s_(s), hash_(std::hash<std::string>()(s))
{
// Automagically forwarding the string in the unordered_map...
};

std::string s_;
std::size_t hash_;
};

int main(int argc, const char * argv[])
{
// Forward the std::string to the prop constructor... but how?
std::unordered_map<prop, int, ...> map( ... );

prop pABC( "ABC" ), pDEF( "DEF" ), pGHI( "GHI" );

map[pABC] = 1;
map[pDEF] = 2;
map[pGHI] = 3;
map[pGHI] = 9;

std::cout << map[pABC] << " : " << pABC.s_ << " : " << pABC.hash_ << std::endl;
std::cout << map[pDEF] << " : " << pDEF.s_ << " : " << pDEF.hash_ << std::endl;
std::cout << map[pGHI] << " : " << pGHI.s_ << " : " << pGHI.hash_ << std::endl;

prop pXXX( "XXX" );
std::cout << map[pXXX] << " : " << pXXX.s_ << " : " << pXXX.hash_ << std::endl;

return 0;
}

我省略了自定义哈希和比较函数,没有它我的想法应该很清楚。

关于c++ - 优化 map : forwarding the key 上的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20005542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com