简体   繁体   English

sub arrays / C++ 中使用迭代器的向量导致崩溃

[英]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://stackoverflow.com/questions/421573/best-way-to-extract-a-subvector-from-a-vector我写了一段代码来使用迭代器打印所有子 arrays,来自这个 [示例解决方案][1] [1]:https://stackoverflow.com/questions/421573/best-way-to-extract-a-subvector -从一个向量

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举个例子 [23, 2, 4, 6, 7] 我最终看到了崩溃,最后抱怨数组太大

o/p 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我签入了 gdb,由于某种原因,数组大小越来越大

As @KamilCuk rightly pointed out problems with your code.正如@KamilCuk 正确指出您的代码存在问题一样。 Reason of the crash is allocation of new vector when i > j .崩溃的原因是当i > j时分配新向量。 Probably you need to change the inner for loop to可能您需要将内部 for 循环更改为

for (int j = i + 1; j <= arr.size(); j++)

Assign i to j in the inner loop and you will see what you expect:在内部循环中将i分配给j ,您将看到您所期望的:

void subArrayPrinter(vector<int>& arr) {
    for (int i = 0; i < arr.size(); i++) {
        for (int j = i; 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 << "Begin " << endl;
    subArrayPrinter(zarray);
}

Outuput:输出:

Begin 

23 
23 2 
23 2 4 
23 2 4 6 
23 2 4 6 7 

2 
2 4 
2 4 6 
2 4 6 7 

4 
4 6 
4 6 7 

6 
6 7 

7 

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

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