如何获取标准::设置的相对索引
How can I get relative index of std::set?
我最近遇到了一个问题。我想获取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;
}
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 嵌套在类中时无法设置成员数据
- 需要帮助设置在C++中使用的Potrace
- 如何在自删除后将对象设置为nullptr
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何在Ubuntu中使用cmake设置qt4
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 如何在boost beast http请求中设置http头
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 如何设置与其背景图像大小相对应的窗口大小?
- 在Visual Studio Code(.json配置)中设置相对于工作区路径的c / c ++项目的包含路径
- 如何在不需要 root 访问权限的情况下为应用程序中的线程设置相对线程优先级
- 如何获取标准::设置的相对索引
- 如何获取设置位中的相对位置
- 在 Visual Studio 中为 SFML 设置相对路径
- 为 SetWaitableTimer 设置相对时间时的算术溢出
- 是否有方法将相对库路径添加到可执行文件以避免设置LD_library_path