我试图检查一个给定的键是否在一个映射中,有点不能这样做:
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中的内容呢?
map<string, string> m;
检查键是否存在,返回出现的个数(map中0/1):
int num = m.count("f");
if (num>0) {
//found
} else {
// not found
}
检查键是否存在,并返回迭代器:
map<string,string>::iterator mi = m.find("f");
if(mi != m.end()) {
//found
//do something to mi.
} else {
// not found
}
在你的问题中,错误操作符<<重载引起的错误,因为p.first是映射<字符串,字符串>,你不能打印出来。试试这个:
if(p.first != p.second) {
cout << p.first->first << " " << p.first->second << endl;
}