查看键是否在c ++映射中存在[重复]

I have a c++ map where the value type is a bool. I need to see if a key exists in the map, and if it doesn't, return false. This is my code right now:

try {
  return board.at[{x, y}];
}
catch (const std::out_of_range& oor) {
  return false;
}

I don't want to use the [] operator because that will initialize the value if it doesn't exist. Is there any way to see if the value exists in the map without a try block?

评论
  • iid
    iid 回复

    You can use std::map::find which will return an iterator the element if found, or .end if not found.

    return board.find({x, y}) != board.end();
    
  • 葬痴心
    葬痴心 回复

    my_map.count({x, y}) is the idiomatic way, and has the advantage of the implicit bool conversion.