将 unordered_map 与动态分配的用户定义 class 结合使用
Using unordered_map with dyanmically-allocated user-defined class
所以我有一个 class、"Room",它有以下代码:
class Room
{
public:
Room(string name, string desc): name(name), desc(desc) {}
void operator=(const Room room)
{
name = room.name;
desc = room.desc;
}
string getName(); //returns this.name
string getDesc(); //returns this.desc
private:
string name; //name of the room
string desc; //description of the room
};
我的 main.cpp 中有一个 unordered_map 类型的全局变量,如下所示:
unordered_map<string, *Room> rooms; //Room's name is the key
我想在一个函数中即时分配房间并将它们添加到我的地图中。我试图这样做:
void builder()
{
Room* room = new Room("Name", "Desc");
rooms[room->getName()] = room;
}
...但是我收到了各种编译器警告。我认为这可能与迭代器或散列有关,或者我没有正确使用指针(这可能都是真的),但大多数情况下 unordered_map 似乎不喜欢使用 Room 或 *Room 进行参数化。我错过了什么吗?
有一些语法错误 *Room
。我有一些小窍门
#include <string>
#include <memory>
#include <unordered_map>
using namespace std;
class Room
{
public:
Room(string name, string desc)
: name(name) // This syntax is called initializer list
, desc(desc)
{
}
void operator = (const Room room)
{
name = room.name;
desc = room.desc;
}
string getName() { return name; }
string getDesc() { return desc; }
private:
string name; //name of the room
string desc; //description of the room
};
// Without using unique_ptr you have a memory leak
// because the is not explicitly called the delete operator on pointers
unordered_map<string, std::unique_ptr<Room> > rooms;
void builder()
{
Room* room = new Room("Name", "Desc");
rooms[room->getName()].reset (room);
}
所以我有一个 class、"Room",它有以下代码:
class Room
{
public:
Room(string name, string desc): name(name), desc(desc) {}
void operator=(const Room room)
{
name = room.name;
desc = room.desc;
}
string getName(); //returns this.name
string getDesc(); //returns this.desc
private:
string name; //name of the room
string desc; //description of the room
};
我的 main.cpp 中有一个 unordered_map 类型的全局变量,如下所示:
unordered_map<string, *Room> rooms; //Room's name is the key
我想在一个函数中即时分配房间并将它们添加到我的地图中。我试图这样做:
void builder()
{
Room* room = new Room("Name", "Desc");
rooms[room->getName()] = room;
}
...但是我收到了各种编译器警告。我认为这可能与迭代器或散列有关,或者我没有正确使用指针(这可能都是真的),但大多数情况下 unordered_map 似乎不喜欢使用 Room 或 *Room 进行参数化。我错过了什么吗?
有一些语法错误 *Room
。我有一些小窍门
#include <string>
#include <memory>
#include <unordered_map>
using namespace std;
class Room
{
public:
Room(string name, string desc)
: name(name) // This syntax is called initializer list
, desc(desc)
{
}
void operator = (const Room room)
{
name = room.name;
desc = room.desc;
}
string getName() { return name; }
string getDesc() { return desc; }
private:
string name; //name of the room
string desc; //description of the room
};
// Without using unique_ptr you have a memory leak
// because the is not explicitly called the delete operator on pointers
unordered_map<string, std::unique_ptr<Room> > rooms;
void builder()
{
Room* room = new Room("Name", "Desc");
rooms[room->getName()].reset (room);
}