Reputation: 397
I'm trying to create a unordered_map that has an integer as a key and a Transition object as the value.... Here's what I have:
Instantiation
unordered_map<int, Transition> transitions;
Transition Class Declaration:
class Transition{
public:
Transition(int n, char r, char m);
~Transition();
int getNextState();
char getReplacement();
char getMovement();
private:
int nextState;
char replacement;
char movement;
};
Adding a transition to the map
// Create transition object
Transition t(r,b,x);
transitions[keyForMap] = t;
I'm getting this error:
/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
Do I need to somehow specify the parameters that the constructor takes somewhere in the instantiation? What am I doing wrong? Thanks for any help ahead of time.
Upvotes: 1
Views: 8172
Reputation: 2290
Your constructor got rid of the default constructor (which is needed).
Upvotes: 0
Reputation:
std::map::operator[]
works as follows:
- If the specified key already exists, it returns a reference to the corresponding value.
- If the specified key doesn't exist, it inserts it, assigns it a default value, and return a reference to this recently created instance of the default value.
For example,
map<string, int> m;
std::cout << m["new_key"]; // This prints the default value for type int, namely '0'.
If your value type does not support a default value (e.g. if it's a custom class that does not have a default constructor), then you can not use std::map::operator[]
.
You can, however, use std::map::insert
to perform the same functionality. The latter will insert a pair directly into your map, without passing by the intermediate step of creating a default value.
Upvotes: 0