How can I know the equal_range didn't find any match cases?
like:
multimap<string,string> mapdic;
pair<multimap<string,string>::iterator,multimap<string,string>::iterator> ret;
// insert some string pairs
ret=mapdic.equal_range(thisUpperCaseName);
if (???)//how to test equal_rang开发者_如何学编程e find nothing?
{
}else{
}
Anyone can help?
Thanks
:)
say your equal_range returns result of type pair
If your result.first == result.second
then it means there is nothing.
If there is even a single element then result.first != result.second
if(ret.first == ret.second)
{
// empty range
}
else
{
//at least an element.
}
Added an example to show 4 different cases of equal_range
return values and how the lower and upper bound values are used to find the existence of the required key.
int main()
{
multimap<string, string> mp{ {"B","0"},{"C","1"},{"C","2"}};
// Case 1: Element exist and both lower/upper bounds are within the range of mp
auto range = mp.equal_range("B");
std::cout << "Lower bound of B is " << range.first->first; // B
std::cout << "Upper bound of B is " << range.second->first; // C
for (auto i = range.first; i != range.second; ++i)
{
std::cout << i->first; // B
}
// Case 2: Element exist and lower bound within the range but not upper bound
range = mp.equal_range("C");
std::cout << "Lower bound of C is " << range.first->first; // C
// std::cout << "Upper bound of C is " << range.second->first; // CRASH
if (range.second == mp.end())
{
std::cout << "Upper bound of C is past-the-last element of mp [mp.end()]";
}
for (auto i = range.first; i != range.second; ++i)
{
std::cout << i->first; // C C
}
// Case 3: Element does NOT exist but both lower/upper bounds within the range of mp
range = mp.equal_range("A");
if (range.first == range.second && range.first != mp.end())
{
std::cout << "Lower bound of A is " << range.first->first; // B
std::cout << "Upper bound of A is " << range.second->first; // B
}
for (auto i = range.first; i != range.second; ++i) // range.first == range.second
{
std::cout << i->first; // NOT executed
}
// Case 4: Element does NOT exist and both lower/upper bounds are out of the range
range = mp.equal_range("D");
if (range.first == range.second && range.first == mp.end())
{
std::cout << "Lower/Upper bounds of D is past-the-last element of mp [mp.end()]";
}
for (auto i = range.first; i != range.second; ++i) // range.first == range.second
{
std::cout << i->first; // NOT executed
}
}
精彩评论