简体   繁体   中英

inserting object into std::map

I have a function bool GateControl::addAuthorization(CardNumber number, const string& name, const string& startTime, const string& endTime) which is supposed to return false if an item was already inside the map and true if is not, if it is not inside the map insert the item in the map. This is what I have:

struct Authorization
{
    Authorization() { }

    Authorization(CardNumber number, const string& name, const string& startTime, const string& endTime)
    : number_(number), name_(name), startTime_(startTime), endTime_(endTime) { }

    CardNumber number_;

    string name_;

    string startTime_;

    string endTime_;
};

typedef map<CardNumber, Authorization> AuthorizationMap;
typedef AuthorizationMap::iterator AuthorizationMapIterator;

typedef vector<Authorization> AuthorizationVector;
bool GateControl::addAuthorization(CardNumber number, const string& name, const string& startTime, const string& endTime)
{
    Authorization item;

    item = Authorization(number, name, startTime, endTime);

    if ( authorizationMap_.find(number) == authorizationMap_.end() ) {
      return false;
    } else {
        authorizationMap_.insert({number, item});

      return true;
    }

}

So, breaking this down, you want to find out if a key (number) exists in a std::map or not?

Use the find operator, as shown here:

if ( AuthorizationMap.find(number) == AuthorizationMap.end() ) {
  // not found
} else {
  // found
}

or, more simply:

// return false if number is already in AuthorizationMap
return (AuthorizationMap.find(number) == AuthorizationMap.end());

Documentation for the find function can be found here: https://www.cplusplus.com/reference/map/map/find/

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