Map issue

Hi everyone,
This is actually the first time I use maps and I have an annoying issue:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Lol
{
public:
Lol(string);
//other things
}

class Thing
{
public:
Lol get(string key)
{
return amap[key]; // error here, no default constructor for Lol
}
private:
map <string, Lol>amap;
}


Then I'm stuck here, I have no idea what to do. Maybe YOU guys have an idea ;)
Thanks
You forgot the semicolons ending the class body.

// error here, no default constructor for Lol

Then why do you not provide a default constructor, which can be empty?

1
2
3
4
5
6
class Lol
{
public:

    Lol() {}
};

OK I have written an empty constructor thanks for the advice ;)
Perhaps a more important issue is to understand why a default constructor is needed here.

From the std::map reference material on this site:

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).


http://www.cplusplus.com/reference/map/map/operator%5B%5D/

At line 13 you could, potentially, be creating a new element in the map, and since you're not assigning any value to it, a default constructor is required.

Have you considered using amap.at(key) instead?
Topic archived. No new replies allowed.