你好我是 C++ 的新手,我想创建一个像这样的数组,但在 C++ 中:
rooms {
1 { 'name' : 'Room1' },
2 { 'name' : 'Room2' }
}
有人可以帮我解决这个问题吗?适合你的时间坦克
最佳答案
定义一个 struct
或 class
来表示房间数据并使用 std::vector
, std::map
或 std::unorderd_map
来存储房间:
#include <iostream>
#include <vector>
#include <map>
struct Room {
std::string name;
Room(std::string _name) : name(_name) {}
Room() {}
};
int main() {
std::vector<Room> rooms{{"Room1"}, {"Room2"}};
std::cout << rooms[0].name << std::endl; // prints "Room1"
std::map<int, Room> roomsMap{
{1, Room{"Room1"}},
{2, Room{"Room2"}}
};
std::cout << roomsMap[1].name << std::endl; // prints "Room1"
return 0;
}
关于C++重构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39349966/