gpt4 book ai didi

类中的 C++ 映射,如何创建成员访问器

转载 作者:行者123 更新时间:2023-11-27 23:32:43 25 4
gpt4 key购买 nike

我是 map 新手。我需要一个为表演构建座位的类(有很多表演)。这是我到目前为止所拥有的:

// header stuff/libraries

Seats::Seats()
{
map< const string, bool > seat;

seat["A1"] = false;
seat["A2"] = false;
/* more seats .. */
}

如果我想更新一个席位,是否需要创建一个访问成员?如果可以的话,我可以举个例子吗?

最佳答案

正如其他人所指出的,您的 map 变量需要是类的数据成员,而不是像您发布的那样在 Seats 构造函数的本地范围内

class Seats {
public:
Seats();
bool GetSeat(const string &);
void SetSeat(const string &, bool);

private:
map< string, bool > seat;

};

Seats::Seats() {
// merely your example values posted.
seat["A1"] = false;
seat["A2"] = false;
}

void Seats::SetSeat(const string &seat_number, bool occupied) {
seat[seat_number] = occupied;
}

bool Seats::GetSeat(const string &seat_number) {
return seat[seat_number];
}

请记住,使用 map 的 [] 运算符可能会导致将元素插入到数据结构中(如果它们尚不存在): link text

T& operator[] ( const key_type& x ); If x does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the map size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

关于类中的 C++ 映射,如何创建成员访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3860606/

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