0

I have the following...

struct MessageLetter{
  char letter;
  int count;
  MessageLetter(char letter, int freq)
  : letter(letter), count(freq)
  {}
};
...
std::map<char, MessageLetter> lList;
...
MessageLetter m = MessageLetter(letter,1);
lList[letter] = m;

When I try to compile I get...

no matching constructor for initialization of 'MessageLetter'
            ::new ((void*)__p) _Tp();

Gotta be something easy anyone have an idea?

2 Answers 2

4
lList[letter] = m;

This line actually defaultly constructs a MessageLetter then returns it by reference, you then assign m to it, calling operator=.

This means that MessageLetter requires a defualt constructor, like so:

MessageLetter() {}

or with C++11:

MessageLetter()=default;

if you don't intend to actually do anything in it.

You can also get away without having to defaultly construct using std::map::insert

lList.insert(std::make_pair(letter), m));

or emplace with c++11:

lList.emplace(letter, { letter, 1 });

http://en.cppreference.com/w/cpp/container/map/insert

http://en.cppreference.com/w/cpp/container/map/emplace

http://en.cppreference.com/w/cpp/container/map/operator_at

Sign up to request clarification or add additional context in comments.

1 Comment

I am not sure your emplace example is actually correct. I would have expected list.emplace(std::piecewise_construct, std::forward_as_tuple(letter), std::forward_as_tuple(letter, 1));
1

The operator[] for an std::map requires that the mapped type be default-constructible (since it first default constructs a new element, then returns a reference to it, and you then assign to that). This isn't the case for you. You should use insert or emplace instead:

lList.insert(std::make_pair(letter, MessageLetter(letter, 1)));

// or

lList.emplace(letter, MessageLetter(letter, 1));

Both functions return information about whether the insertion was possible (the key may already have existed) and location of the element with the given key.

1 Comment

This works too thanks but I think the next one is a little more detailed so I am accepting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.