简体   繁体   English

Fenwick树(二叉索引树)中的分割错误

[英]Segmentation fault in Fenwick tree(Binary Index Tree)

I've realised Fenwick Tree, but when i try to find sum on segment there is Segmentation Fault 11. 我已经意识到Fenwick树,但是当我尝试在分段上找到总和时,就会出现分段错误11。

#include <vector>
#include <iostream>
using namespace std;


class Fenwick{
public:
    Fenwick();
    int sum(int l, int r);
    void update(int pos, int value);
    void print(int i);
private:
    vector<int> fentr;
    int sum(int i);
};
Fenwick::Fenwick(){
}

void Fenwick::print(int i){
    cout<<fentr[i];
}
int Fenwick::sum(int l, int r){
    return sum(r)-sum(l-1);
}
int Fenwick::sum(int i){
    int result=0;
    // while(i>=0){
    //  result+=fentr[i];
    //  i=(i&(i+1))-1;
    // }
    for(int j=i; j>=0; j=(i&(i+1))-1){
        result+=fentr[j];
    }
    return result;
}

void Fenwick::update(int pos, int value){
    while (pos<fentr.size()){
        fentr[pos]+=value;
        pos=pos | (pos+1);
    }
}


int main(){
    Fenwick a;
    a.update(0, 1);
    a.update(1, 2);
    a.update(2, 3);
    a.update(3, 4);
    a.update(4, 5);
    int j = a.sum(0,2);
    cout<<j;


}

Also, have i done it right? 另外,我做对了吗? I mean, i completely understood idea of Fenwick tree, I just can't find out what we must do with initial array? 我的意思是,我完全了解Fenwick树的概念,只是无法确定初始数组必须做什么? May be i need to pass as an argument to Fenwik class and then working with him? 可能我需要将论点传递给Fenwik班级,然后与他一起工作? Or just a lot of updates? 还是只是很多更新? Thank you in advance. 先感谢您。

As far as I can see, you haven't initialized the fentr vector. 据我所知,您尚未初始化fentr向量。 This won't fail on update, since you're looping to fentr.size() , but it will segfault on the call to sum . 由于您要循环到fentr.size() ,因此更新不会失败,但这将对sum的调用造成段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM