samedi 25 juillet 2020

sub arrays / vectors in C++ using iterators is causing a crash

I wrote a piece of code to print all sub arrays using Iterators, from this [example solution][1] [1]: https://ift.tt/3jAmLIS

void printarray(std::vector<int> array) {
    for (auto a : array) {
        std::cout << a <<" ";
    }
    std::cout<< std::endl;
}

void subArrayPrinter(vector<int>& arr) {
    for (int i = 0; i < arr.size(); i++) {
        for (int j = 2; j <= arr.size(); j++) {
            std::vector<int> newVec(arr.cbegin() + i, arr.cbegin() + j);
            printarray(newVec);
        }
    }
}

int main() {
    std::vector<int> zarray = {23, 2, 4, 6, 7};
    std::cout << subArrayPrinter(zarray) << std::endl;
}

for an example [23, 2, 4, 6, 7] I see a crash eventually which complains of array too big at the end

o/p

23 2 4 6 7 
23 2 
23 2 4 
23 2 4 6 
23 2 4 6 7 
2 
2 4 
2 4 6 
2 4 6 7 
        // <- the array size is zero here, but didnt see this for the first sub array case 
4 
4 6 
4 6 7 
terminate called after throwing an instance of 'std::length_error'
  what():  cannot create std::vector larger than max_size()
Aborted (core dumped)

I checked in gdb, for some reason the array size is getting huge

Aucun commentaire:

Enregistrer un commentaire