我有一张 STL map 和一个范围 [lo, hi]。
在 map 中找到适合此范围的所有元素的最佳方法是什么?
UDT:
关于upper_bound和low_bound的问题是:
例如,我有一个包含 {1, 2, 7, 8} 的集合或映射,我的范围是 [3,6]。 lower_bound 将指向 7,upper_bound 将指向 2。假设我不想删除 smith,而只是写出一个范围内的所有元素。我该怎么做?在这种情况下删除的复杂性如何?
最佳答案
如果您使用的是 std::map,它已经排序,您可以使用来自 cplusplus.com 的 lower_bound/upper_bound 示例:
// map::lower_bound/upper_bound
#include <iostream>
#include <map>
int main ()
{
std::map<char,int> mymap;
std::map<char,int>::iterator itlow,itup;
mymap['a']=20;
mymap['b']=40;
mymap['c']=60;
mymap['d']=80;
mymap['e']=100;
itlow=mymap.lower_bound ('b'); // itlow points to b
itup=mymap.upper_bound ('d'); // itup points to e (not d!)
mymap.erase(itlow,itup); // erases [itlow,itup)
// print content:
for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
return 0;
}
关于c++ - 如何在 STL map(set) 中查找范围内的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30209168/