如何获取标准::设置的相对索引

How can I get relative index of std::set?

本文关键字:设置 相对 索引 标准 何获取 获取      更新时间:2023-10-16

我最近遇到了一个问题。我想获取std::set元素的相对索引。例如,如果std::set存储{1, 2, 4, 6, 9, 15},并且我想找到元素{4}并有效地获取其相对索引{2}。当然,我可以写std::distance(myset.begin(), myiterator),但此操作的复杂性O(n*logn)。如果我可以访问真正的红黑std::set树,我会运行rb_tree_node_pos(见下文(,这是O(logn)。这正是相对指数。有谁知道我怎样才能得到真正的树?下面是代码示例:

#include <iostream>
#include <set>
using namespace std ;
int rb_tree_node_pos(rb_tree_node *node) {
  //function that finds relative index of tree node
  if (node->parent==NULL) return rb_tree_size(node->left) ;
  else return rb_tree_node_pos(node->parent)+rb_tree_size(node->left)+1 ;_
}
int main () {
  set<int> myset ;
  //... reading some data in myset
  int find_int ;
  cin >> find_int ;
  set<int>::iterator myit=myset.find(find_int) ;
  int find_index=distance(myset.begin(), myit) ; // O(n*log(n)), to slow!!!
  find_index=rb_tree_node_pos(myit->get_rb_tree()) ; // that's O(logn)
  cout << find_index << endl ;
  return 0 ;
}

一般来说,我想要能够保持以下操作的数据结构:1.插入元素,2.删除元素,3.打印出元素的相对索引。我认为有一种方法可以从STL中"挖掘"它。

感谢@Fanael,谁找到了解决方案!我们可以使用 GNU 基于策略的数据结构 (PBDS( 来实现此数据结构。下面是代码示例:

#include <iostream>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef
tree<
  int,
  null_type,
  less<int>,
  rb_tree_tag,
  tree_order_statistics_node_update>
ordered_set;
int main()
{
  ordered_set myset;
  //....reading some data to myset
  int find_int ;
  cin >> find_int ;
  find_index=myset.order_of_key(find_int) ;
  cout << find_index << endl ;
  return 0;
}

你可以从这里和这里了解更多关于GNU PBDS的信息。感谢所有帮助过的人!

如果使用 std::set,你可以找到具有线性复杂度的元素索引:

int Search (const std::set<int>& a, int value)
{
    int c=0;
    for(auto&& i: a)
    {
        if(i==value) return c;
        ++c;
    }
    return -1;
}
int main()
{
    std::set <int> a{1, 2, 4, 6, 9, 15};
    std::cout << Search(a,4) << std::endl;
}

但是如果你使用排序数组和二叉搜索,复杂度将是O(log(n((。

int Binary_search (const std::vector<int>& a, int value)
{
    int l=0;
    int r=a.size()-1;
    while(l<=r)
    {
        int m=(l+r+1)/2;
        if(a[m]==value) return m;
        else if(a[m]>value) r=m-1;
        else l=m+1;
    }
    return -1;
}
int main()
{
    std::vector <int> a{1, 2, 4, 6, 9, 15};
    std::cout << Binary_search(a,4) << std::endl;
}