2016-09-06 54 views
0

嗨,我是新的C++,我想创建一个数组这样,但C++:C++重构阵列

rooms { 

     1 { 'name' : 'Room1' }, 
     2 { 'name' : 'Room2' } 

    } 

有人可以帮助我?您的时间

+0

您所要求的字典(图),而不是名单。 – Uriel

+0

像'std :: vector >'? –

+0

查看http://www.cplusplus.com/doc/tutorial/structures/上的结构数组示例,尽管您可能希望将它们存储在比数组更好的容器中:set,list或vector ,或索引类型作为地图,会更合适。 – Lanting

回答

2

坦克定义structclass代表房间的数据,并使用std::vectorstd::mapstd::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; 
}