我试图检查一个给定的键是否在一个映射中,有点不能这样做:
typedef map<string,string>::iterator mi;
map<string, string> m;
m.insert(make_pair("f","++--"));
pair<mi,mi> p = m.equal_range("f");//I'm not sure if equal_range does what I want
cout << p.first;//I'm getting error here
那么我怎么打印p中的内容呢?
要检查映射中是否存在特定的键,可以通过以下方式之一使用count成员函数:
m.count(key) > 0
m.count(key) == 1
m.count(key) != 0
map::find的文档说:“另一个成员函数map::count可用于检查特定键是否存在。”
map::count的文档说:“因为map容器中的所有元素都是唯一的,所以函数只能返回1(如果找到元素)或0(否则)。”
要通过已知存在的键从映射中检索值,请使用map::at::
value = m.at(key)
与map::operator[]不同,如果指定的键不存在,map::at将不会在映射中创建一个新的键。