C++程序在执行时什么都不做
C++ program does nothing when executed
我在 Ubuntu 18.04 使用它附带的默认 c++ 编译器。我正在尝试从键盘获取所需的矢量大小,并最终在 makeGaps 函数中用 i 的递增值填充一个矢量。然后我想 return 一个填充向量到我的变量 x。但是,当我 运行 下面的代码时,在它显示 "enter gap size" 之后,即使我提供了一个整数,它也什么都不做。没有输出,没有错误,而且在代码块中,所有调试器图标都变灰了。代码也不
终止,我不知道出了什么问题。
#include <iostream>
#include <vector>
using namespace std;
vector<int> makeGaps (int size){
vector<int> vectorOfGaps(size);
for(int i = 0; i <= vectorOfGaps.size();i++){
vectorOfGaps.push_back(i);
}
return vectorOfGaps;
}
void printV(vector<int> collection){
for (int i = 0; i <= collection.size(); i++){
cout << collection[i]<< '\n';
}
}
int main()
{ //get the number of gaps required
int numberOfGaps;
cout << "Enter gap size";
cin >> numberOfGaps;
vector<int> x = makeGaps(numberOfGaps);
printV(x);
return 0;
}
此外,如果我 运行 在 vs code 附带的终端中使用它,它会使我的机器崩溃。
c++ 中的向量是动态调整大小的。
您可以在构造函数中创建一个不带 size 参数的向量,然后像这样推送元素的 size 数量:
vector<int> makeGaps (int size){
vector<int> vectorOfGaps;
for(int i = 0; i < size;i++){
vectorOfGaps.push_back(i);
}
return vectorOfGaps;
}
编辑:另外,正如有人已经在您的评论中指出的那样,您的 for 循环中似乎出现了一个错误。如果 for 循环运行到 x <= size
,它将迭代 size+1
次。
我在 Ubuntu 18.04 使用它附带的默认 c++ 编译器。我正在尝试从键盘获取所需的矢量大小,并最终在 makeGaps 函数中用 i 的递增值填充一个矢量。然后我想 return 一个填充向量到我的变量 x。但是,当我 运行 下面的代码时,在它显示 "enter gap size" 之后,即使我提供了一个整数,它也什么都不做。没有输出,没有错误,而且在代码块中,所有调试器图标都变灰了。代码也不 终止,我不知道出了什么问题。
#include <iostream>
#include <vector>
using namespace std;
vector<int> makeGaps (int size){
vector<int> vectorOfGaps(size);
for(int i = 0; i <= vectorOfGaps.size();i++){
vectorOfGaps.push_back(i);
}
return vectorOfGaps;
}
void printV(vector<int> collection){
for (int i = 0; i <= collection.size(); i++){
cout << collection[i]<< '\n';
}
}
int main()
{ //get the number of gaps required
int numberOfGaps;
cout << "Enter gap size";
cin >> numberOfGaps;
vector<int> x = makeGaps(numberOfGaps);
printV(x);
return 0;
}
此外,如果我 运行 在 vs code 附带的终端中使用它,它会使我的机器崩溃。
c++ 中的向量是动态调整大小的。
您可以在构造函数中创建一个不带 size 参数的向量,然后像这样推送元素的 size 数量:
vector<int> makeGaps (int size){
vector<int> vectorOfGaps;
for(int i = 0; i < size;i++){
vectorOfGaps.push_back(i);
}
return vectorOfGaps;
}
编辑:另外,正如有人已经在您的评论中指出的那样,您的 for 循环中似乎出现了一个错误。如果 for 循环运行到 x <= size
,它将迭代 size+1
次。