Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何计算std::set中给定元素之前的元素数_C++_Stdset - Fatal编程技术网

C++ 如何计算std::set中给定元素之前的元素数

C++ 如何计算std::set中给定元素之前的元素数,c++,stdset,C++,Stdset,我想在给定元素的下界之前找到集合中不存在的元素,我考虑将指针算法与std::set::iterators结合使用,因为它们的行为类似于指针,下面是我尝试的: set<int>q; set<int>::iterator curr; set<int>::iterator strt; l = num.size(); q.insert(num[l-1]); strt = q.begin(); temp = 1; int x; for(int i=l-2;i>=0

我想在给定元素的下界之前找到集合中不存在的元素,我考虑将指针算法与std::set::iterators结合使用,因为它们的行为类似于指针,下面是我尝试的:

set<int>q;
set<int>::iterator curr;
set<int>::iterator strt;
l = num.size();
q.insert(num[l-1]);
strt = q.begin();
temp = 1;
int x;
for(int i=l-2;i>=0;i--)
{
    curr = q.lower_bound(num[i]);
    if(curr == q.end())
        stats.push_back({temp,0});
    else
    {
        x = curr-strt;//ERROR
        stats.push_back({x,temp-x});
    }
    q.insert(num[i]);
    temp++;
}
setq;
set::迭代器curr;
set::迭代器strt;
l=数值大小();
q、 插入(数字[l-1]);
strt=q.begin();
温度=1;
int x;
对于(int i=l-2;i>=0;i--)
{
curr=q.下界(num[i]);
如果(curr==q.end())
stats.push_back({temp,0});
其他的
{
x=curr strt;//错误
stats.push_back({x,temp-x});
}
q、 插入(数量[i]);
temp++;
}

有没有办法在给定元素的下限之前找到集合中不存在的元素?

您必须从头到脚遍历集合,以计算元素的数量。这有一个很好的解释:

x = std::distance(strt, curr);
curr strt
这样的算术运算只为随机访问迭代器定义,其中计算可以在恒定时间内完成。类似于
distance
的函数将适用于更一般的迭代器类型,但如果迭代器不直接支持该运算符,则可能速度较慢。

使用,可以在对数时间内进行动态顺序统计


我曾经写过一次,后来又写过一次。

a
O(n)
,是否有其他时间复杂度较低的方法,或者是否有更合适的容器?@Sab:根据您正在做的其他事情,排序数组/向量可能会更好。您可以使用
std::lower_bound
等在对数时间中搜索,并在恒定时间中查找迭代器距离。维护排序顺序可能需要更多的工作。@MikeSeymour需要注意的是,“您必须从开始到找到的点遍历集合”通常不是平衡树的属性,特别是STL树。你可能想在下面看到我的答案。