gpt4 book ai didi

C++ unordered_multimap 插入散列

转载 作者:行者123 更新时间:2023-11-30 05:41:15 25 4
gpt4 key购买 nike

我在这里要疯了。我通过谷歌搜索找到了 1 个不错的示例,其中人们将 unordered_map 与枚举类和哈希函数一起使用,但没有任何运气。我设法找到的那些最终总是说“改用 map ”。

我正在尝试执行以下操作:

Enum class facing 是我的 Sprite 正在看的方向。

Enum class Action 是我的 Sprite 正在执行的操作。

Animation 是一个包含不同动画的类,我稍后会调用它。

容器应该是这样的:

map

图中可以有多个FACING作为key,pair中可以有多个ACTION。

例子:

map<LEFT, pair<ATTACK, attackAnimation>
map<LEFT, pair<IDLE, idleAnimation>
map<LEFTUP, pair<IDLE, idleAnimation>

这是一个简化的一切

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

template <typename T>
struct Hash
{
typedef typename std::underlying_type<T>::type underlyingType;
typedef typename std::hash<underlyingType>::result_type resultType;
resultType operator()(const T& arg) const
{
std::hash<underlyingType> hasher;
return hasher(static_cast<underlyingType>(arg));
}
};

class Animation
{
private:
std::string str;

public:
Animation(std::string _string)
{
this->str = _string;
}

std::string& GetString()
{
return this->str;
}
};

class Bullshit
{
public:
enum class Action
{
Attack,
Move
};

enum class Facing
{
Right,
Up,
Left
};

Bullshit()
{

}

std::unordered_multimap<Bullshit::Facing, std::pair<Bullshit::Action, std::unique_ptr<Animation>>,Hash<Bullshit::Facing>>& GetlistAnimation()
{
return this->listAnimation;
}

private:
std::unordered_multimap<Bullshit::Facing, std::pair<Bullshit::Action, std::unique_ptr<Animation>>,Hash<Bullshit::Facing>> listAnimation;
};


int main()
{
Bullshit bull;
auto myList = bull.GetlistAnimation();

std::unique_ptr<Animation> anim(new Animation("test"));
myList.insert(std::make_pair(Bullshit::Facing::Up, std::make_pair(Bullshit::Action::Attack, std::move(anim))));

std::cin.get();
return 0;
}

错误代码:

error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
1> with
1> [
1> _Ty=Animation
1> ]
1> c:\program files (x86)\microsoft visual studio 11.0\vc\include\memory(1447) : see declaration of 'std::unique_ptr<_Ty>::unique_ptr'
1> with
1> [
1> _Ty=Animation
1> ]
1> This diagnostic occurred in the compiler generated function 'std::pair<_Ty1,_Ty2>::pair(const std::pair<_Ty1,_Ty2> &)'
1> with
1> [
1> _Ty1=Bullshit::Action,
1> _Ty2=std::unique_ptr<Animation>
1> ]

最佳答案

这里

auto myList = bull.GetlistAnimation();

myList 推导的类型是std::unordered_map<.....> ,也就是说,它不是引用。并且无法创建拷贝,因为 map 包含 unique_ptr秒。你的意思是

auto& myList = bull.GetlistAnimation();

或者在 C++14 中,

decltype(auto) myList = bull.GetlistAnimation();

关于C++ unordered_multimap 插入散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31207633/

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