Segmentation fault in Fenwick tree(Binary Index Tree)

118 views Asked by At

I've realised Fenwick Tree, but when i try to find sum on segment there is Segmentation Fault 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? May be i need to pass as an argument to Fenwik class and then working with him? Or just a lot of updates? Thank you in advance.

1

There are 1 answers

0
Ivan Vergiliev On BEST ANSWER

As far as I can see, you haven't initialized the fentr vector. This won't fail on update, since you're looping to fentr.size(), but it will segfault on the call to sum.