gpt4 book ai didi

C++重构数组

转载 作者:行者123 更新时间:2023-11-28 02:01:33 25 4
gpt4 key购买 nike

你好我是 C++ 的新手,我想创建一个像这样的数组,但在 C++ 中:

    rooms {

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

}

有人可以帮我解决这个问题吗?适合你的时间坦克

最佳答案

定义一个 structclass 来表示房间数据并使用 std::vector , std::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;
}

关于C++重构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39349966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com