简体   繁体   中英

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

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 ); 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).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM