Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Inserting a class into a map container

I have a map in C++ and I wish to input my class as the value, and a string as the key. When I try to, I get an error 'Scene_Branding' : illegal use of this type as an expression I get an illegal use of this type as an expression, and I can't seem to find out why. Here is some code.

 string CurrentScene = "Scene_Branding";
 map<string, Scene> Scenes;
 Scenes.insert(std::make_pair("Scene_Branding", Scene_Branding));  //<-- Illegal Error parameter 2

and here is Scene Branding header..

#ifndef Scene_Branding_H
#define Scene_Branding_H

#include "Scene.h"
#include <iostream>
#include <string>


class Scene_Branding : Scene
{
public:
 Scene_Branding();
 ~Scene_Branding();
 void Draw();
};

#endif

and here is Scene header..

#ifndef Scene_H
#define Scene_H

#include <iostream>
#include <string>

class Scene
{
public:
 Scene();
 ~Scene();
 virtual void Draw();

};

#endif

and here is there cpp files.

Scene cpp.

#include "Scene.h"

Scene::Scene()
{

}
Scene::~Scene()
{

}
void Scene::Draw(){
 std::cout << "Hey";
}

Scene_Branding cpp

#include "Scene_Branding.h"

Scene_Branding::Scene_Branding()
{

}

Scene_Branding::~Scene_Branding()
{

}

void Scene_Branding::Draw()
{
 std::cout << "Drawing from Scene_branding";
}
like image 754
Fouf Avatar asked Feb 17 '10 14:02

Fouf


People also ask

How do you add elements to a map?

The standard solution to insert new elements into a map is using the std::map::insert function. It inserts the specified key-value pair into the map only if the key already doesn't exist. If the key already exists in the map, the element is not inserted.

What is the complexity of std::map :: insert () method?

Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.

Does map insert overwrite?

insert() doesn't overwrite.

How do you assign a value to a map in C++?

insert( make_pair( std::move(key), std::move(value) ) ) is going to be close to map. emplace( std::move(key), std::move(value) ) . If there is an object at the key location, then [] will call operator= , while insert / emplace will destroy the old object and create a new one.


2 Answers

First, don't store objects themselves in the map, store pointers to your objects.

Second, you need to give an instance of Scene_Branding to std::make_pair, not the class itself.

EDIT: Here's how you go about storing pointers:

 string CurrentScene = "Scene_Branding";
 map<string, Scene*> Scenes;
 Scenes.insert(std::make_pair("Scene_Branding", new Scene_Branding()));

But, since you asked this type of question, i recommend you read a good c++ book for further grasping of concepts like pointers.

like image 151
erelender Avatar answered Oct 05 '22 01:10

erelender


Try:

Scenes.insert(std::make_pair("Scene_Branding", Scene_Branding()));
like image 27
Alexander Gessler Avatar answered Oct 05 '22 01:10

Alexander Gessler