【问题标题】:Is there a TreeSet data structure equivalent in C++ with similar functions在 C++ 中是否有等效的 TreeSet 数据结构具有类似的功能
【发布时间】:2018-04-28 15:41:42
【问题描述】:

我需要在 C++ 中使用 Tree Set 数据结构(在 java 中可用),并使用 TreeSet.lower(i) 和 TreeSet.higher(i) 之类的函数 - > 它返回的元素只是更低,只是高于给定树集中的 i。有 STL 吗?

编辑: 以下是我需要的功能,我想知道如何使用upper_bound和lower_bound函数来做到这一点:

for (int i = 1; i<10; i++) myset.insert(i * 10); // 10 20 30 40 50 60 70 80 90
int k = 50;  // I need 40 and 60
set<int>::iterator itr = myset.find(k);

if (itr != myset.end()) {
    // Found the element
    itr--; // Previous element;
    cout << *(itr); //prints 40
    itr++; // the element found
    itr++; // The next element
    cout << *(itr);  // prints 60
}

【问题讨论】:

    标签: java c++ data-structures set treeset


    【解决方案1】:

    使用std::set,它通常实现为二叉搜索树。

    它的insert()erase()find() 方法的大小是对数的,但如果给出提示可以做得更好。对数复杂度参考Java TreeSet

    我认为您应该对std::lower_boundstd::upper_bound 感兴趣,std::lower_bound 将迭代器返回到下限,std::upper_bound 将迭代器返回到上限。

    【讨论】:

      【解决方案2】:

      您可以使用std::set
      std::set::lower_boundstd::set::upper_bound

      【讨论】:

      • std::set 非常适合这种情况。谢谢@dani
      【解决方案3】:

      您可以在此处使用 std::set。 对于您的功能,您可以使用函数 upper_bound(i) 和 lower_bound(i) 但请注意它们的工作方式与 TreeSet.lower(i) 和 TreeSet.higher(i) 不同。

      lower_bound(const i) - 返回一个迭代器,指向容器中不被认为在 i 之前的第一个元素(即,它是等价的或在之后的),或设置: :end 如果所有元素都被认为在 i 之前。

      upper_bound(const i) – 返回一个迭代器,指向容器中被认为在 i 之后的第一个元素,如果没有元素被认为在 i 之后,则返回 set::end。

      for (int i = 1; i<10; i++) myset.insert(i * 10); // 10 20 30 40 50 60 70 80 90
      int k = 50; 
      set<int>::iterator itlow,itup;
      
      itlow=myset.lower_bound (k);  
      itup=myset.upper_bound (k);
      
      if(itlow!=myset.begin()){
         itlow--;
         cout << *itlow;  // 40 will print
      }
      cout << *itup;  // 60 will print
      

      【讨论】:

        猜你喜欢
        • 2011-02-19
        • 2015-01-11
        • 1970-01-01
        • 1970-01-01
        • 2012-03-21
        • 2011-06-13
        • 1970-01-01
        • 1970-01-01
        • 2010-12-07
        相关资源
        最近更新 更多