我写了一段代码,从这个[示例解决方案][1]中使用Iterator打印所有子数组[1] :https://stackoverflow.com/questions/421573/best-way-to-extract-a-subvector-from-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,由于某种原因,数组大小变得巨大
在内部循环中将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
As@KamilCuk正确地指出了代码中的问题。崩溃的原因是i > j
时分配了新的矢量。可能您需要将内部for循环更改为
for (int j = i + 1; j <= arr.size(); j++)