c++ - 如何在 STL map(set) 中查找范围内的所有元素

标签 c++ dictionary stl

我有一张 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/

相关文章:

c++ - 为什么 std::vector 没有释放方法?

c++ - SDL C++ TTF 一段时间后随机消失(并且不会回来)

c# - 从 c# 调用 c++ 函数指针

python - 持久字典,其中键可以是任何可哈希的

c++ - 从标准 I\O 流读取和写入会导致错误

c++ - 将 std::unique_ptr 移动到 std::vector 内的新位置

c++ - C++ 服务器编程

c++ - 在 C++ 中从 C 库正确初始化 typedef 结构

python - 查找其键与子字符串匹配的字典项

Python - 通过键显示值的字典