提问者:小点点

C++中使用迭代器的子数组/向量会导致崩溃


我编写了一段使用迭代器打印所有子数组的代码,来自以下[示例解决方案][1][1]:https://stackoverflow.com/questions/421573/best-way-to-extract-a-subvector-fro-a-vector

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;
}

举个例子[23,2,4,6,7],我最终看到一个崩溃,抱怨数组在结尾太大

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)

我签入了gdb,由于某种原因,数组的大小变得很大


共2个答案

匿名用户

正如@Kamilcuk正确指出的那样。 崩溃的原因是当i>时分配了新的向量; j。 可能需要将内部for循环更改为

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

匿名用户

在内循环中将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 

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|迭代|器|子|数组|向量|导致|崩溃)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?