我试图检查一个给定的键是否在一个映射中,有点不能这样做:
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中的内容呢?
比较std::map::find和std::map::count的代码,我会说第一个可能会产生一些性能优势:
const_iterator find(const key_type& _Keyval) const
{ // find an element in nonmutable sequence that matches _Keyval
const_iterator _Where = lower_bound(_Keyval); // Here one looks only for lower bound
return (_Where == end()
|| _DEBUG_LT_PRED(this->_Getcomp(),
_Keyval, this->_Key(_Where._Mynode()))
? end() : _Where);
}
size_type count(const key_type& _Keyval) const
{ // count all elements that match _Keyval
_Paircc _Ans = equal_range(_Keyval); // Here both lower and upper bounds are to be found, which is presumably slower.
size_type _Num = 0;
_Distance(_Ans.first, _Ans.second, _Num);
return (_Num);
}
template <typename T, typename Key>
bool key_exists(const T& container, const Key& key)
{
return (container.find(key) != std::end(container));
}
当然,如果你想要更花哨一点,你总是可以模板化一个函数,同时取一个已找到的函数和一个未找到的函数,就像这样:
template <typename T, typename Key, typename FoundFunction, typename NotFoundFunction>
void find_and_execute(const T& container, const Key& key, FoundFunction found_function, NotFoundFunction not_found_function)
{
auto& it = container.find(key);
if (it != std::end(container))
{
found_function(key, it->second);
}
else
{
not_found_function(key);
}
}
像这样使用它:
std::map<int, int> some_map;
find_and_execute(some_map, 1,
[](int key, int value){ std::cout << "key " << key << " found, value: " << value << std::endl; },
[](int key){ std::cout << "key " << key << " not found" << std::endl; });
缺点是要想出一个好名字,“find_and_execute”是尴尬的,我不能想出任何更好的在我的头顶…
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;
}