正在尝试将对象放置到无序映射中

Trying to place objects into unordered_map

本文关键字:无序 映射 对象      更新时间:2023-10-16

我正在尝试创建一个以整数为键、以Transition对象为值的无序映射。。。。这是我的:

实例化

unordered_map<int, Transition> transitions;

过渡级声明:

class Transition{
    public:
            Transition(int n, char r, char m);
            ~Transition();
            int getNextState();
            char getReplacement();
            char getMovement();
    private:
            int nextState;
            char replacement;
            char movement;
};

向地图添加转换

// Create transition object
Transition t(r,b,x);
transitions[keyForMap] = t;

我得到这个错误:

/usr/include/c++/4.7/bits/hashtable_policy.h:445:24: error: no matching function for call to ‘Transition::Transition()’
/usr/include/c++/4.7/bits/hashtable_policy.h:445:24: note: candidates are:
In file included from ball_p1.cpp:6:0:
Transition.h:4:3: note: Transition::Transition(int, char, char)
Transition.h:4:3: note:   candidate expects 3 arguments, 0 provided
Transition.h:1:7: note: constexpr Transition::Transition(const Transition&)
Transition.h:1:7: note:   candidate expects 1 argument, 0 provided

我是否需要以某种方式指定构造函数在实例化中使用的参数?我做错了什么?感谢您提前提供的帮助。

我总是使用map.insert(std::make_pair(keyForMap, transition));

std::map::operator[]的工作原理如下:
-如果指定的键已经存在,它将返回对相应值的引用。
-如果指定的键不存在,它会插入它,为它指定一个默认值,并返回对最近创建的默认值实例的引用。

例如,
map<string, int> m; std::cout << m["new_key"]; // This prints the default value for type int, namely '0'.

如果您的值类型不支持默认值(例如,如果它是一个没有默认构造函数的自定义类),则不能使用std::map::operator[]。但是,您可以使用std::map::insert来执行相同的功能。后者将直接在地图中插入一对,而不经过创建默认值的中间步骤。

您的构造函数去掉了默认构造函数(这是必需的)。