[英]C++ map in a class, how do I make a member accessor
I'm new to maps. 我是新来的地图。 I need a class that constructs seating for a performance (there are many performances).
我需要一个为表演构建座位的类(有很多表演)。 Here's what I have so far:
这是我到目前为止的内容:
// header stuff/libraries
Seats::Seats()
{
map< const string, bool > seat;
seat["A1"] = false;
seat["A2"] = false;
/* more seats .. */
}
Do I need to create an access member if I want to update a seat? 如果要更新座位,是否需要创建访问成员? If can so can I have an example please?
如果可以的话,我可以举个例子吗?
as others have indicated, your map variable needs to be a data member of the class not in the local scope of the Seats constructor as you've posted 正如其他人指出的那样,您的地图变量必须是该类的数据成员,而不是您发布的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];
}
keep in mind using the map's [] operator though can cause elements to be inserted into the data structure if they do not exist yet: link text 请记住使用地图的[]运算符,但是如果元素尚不存在,可能会导致将其插入数据结构中: 链接文本
T& operator[] ( const key_type& x );
T&运算符[](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.
如果x与容器中任何元素的键都不匹配,则该函数将使用该键插入一个新元素,并返回对其映射值的引用。 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).
请注意,即使未将映射值分配给元素(元素是使用其默认构造函数构造的),这也会始终将映射大小增加一。
This might get you started. 这可能会让您入门。
class Seats {
private: // private section: implementation details here
set< string > reservations;
public: // public section: accessors here
bool is_reserved( string const &id ) const {
return reservations.count( id );
}
bool reserve( string const &id ) { // return false if res. already existed
return reservations.insert( id ).second;
}
};
If you want to use a container (like std::map
) as a data member in a class, you need to put it with the rest of the data members for the class, in the class definition. 如果要使用容器(如
std::map
)作为类中的数据成员,则需要将其与该类的其余数据成员一起放在类定义中。
A curios (intentional) property of std::map is that operator[]
default constructs values for keys that aren't already in the collection, so unless you actually need to get a list of the ( false
by default) keys, there's no need to initialize them. std :: map的一个有意思的(有意的)属性是
operator[]
默认为集合中尚未存在的键构造值,因此,除非您实际上需要获取(默认为false
)键的列表,否则没有需要初始化它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.