如何为std :: multimap的给定键获取"previous"项的迭代器(或值)?

Pol*_*hic 2 c++ std multimap

对于我来说,我想获得给定密钥之前的项目std::multimap.

对于在给定键之后的项目,我可以简单地使用std::multimap::upper_bound(它将返回具有更大的键然后给定的元素).但遗憾的是,std::multimap::lower_bound返回带有"低或相等 "键的元素.

样本取自http://www.cplusplus.com/reference/map/multimap/lower_bound/:

mymultimap.insert(std::make_pair('a',10));
mymultimap.insert(std::make_pair('b',121));
mymultimap.insert(std::make_pair('c',1001));
mymultimap.insert(std::make_pair('c',2002));
mymultimap.insert(std::make_pair('d',11011));
mymultimap.insert(std::make_pair('e',44));

itlow = mymultimap.lower_bound ('b');  // itlow points to b
itup = mymultimap.upper_bound ('d');   // itup points to e (not d)
Run Code Online (Sandbox Code Playgroud)

作为参数提供a时,如何获取迭代器(或值)b?

Bar*_*rry 5

您可以使用lower_bound,但有两个边缘情况需要考虑:它返回begin()并返回end():

auto itfound = mymultimap.lower_bound('b');
if (itfound == mymultimap.begin()) {
    // 'b', or something past 'b', is the first item
    // or the map is empty
    // what to do here?
}
else if (itfound == mymultimap.end()) {
    // there does not exist an item >= 'b'
    // what to do here? possibly std::prev(end()) ?
}
else {
    // ok cool, we found something in the middle
    // just back up
    --itfound;

    // do stuff with itfound here
}
Run Code Online (Sandbox Code Playgroud)