[英]C++ refactoring arrays
Hi I'm new at C++ and I want to create an array like this but in C++: 嗨,我是C ++的新手,我想在C ++中创建一个像这样的数组:
rooms {
1 { 'name' : 'Room1' },
2 { 'name' : 'Room2' }
}
Can someone help me with this? 有人可以帮我弄这个吗? Tanks for your time 你的时间的坦克
Define a struct
or class
to represent the room data and use a std::vector
, std::map
or std::unorderd_map
to store the rooms: 定义一个表示房间数据的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.