c++ - 如何制作数组
问题描述
我想在数组中创建 n 个元素。在第一行中我要求给出元素的数量,在第二行中我要求给出实际元素。我试过这段代码
int main() {
int first_line;
cin >> first_line;
int second[first_line];
cin>>second;
cout<< second;
return 0;
}
输入应该看起来像
input
8
1 2 3 4 5 6 7 8
output
1 2 3 4 5 6 7 8
我需要将第二行放在整数数组中。
解决方案
数组(至少在 C++ 中定义)根本无法满足您的要求。
你真正要找的是 a std::vector
,它做得很好。
int main() {
int first_line;
cin >> first_line;
std::vector<int> second(first_line);
for (int i=0; i<first_line; i++) {
int temp;
cin>>temp;
second.push_back(temp);
}
for (auto i : second) {
cout<< i << ' ';
}
cout << "\n";
return 0;
}
推荐阅读
- vhdl - Modelsim 无法在 rb 模式下打开 VHDL 文件“memfile.dat”
- javafx - JavaFX。如何实现自定义 TableCell?
- php - PHPUnit 在本地工作,但 TravisCI 上的一些测试失败 - 状态代码 [500]
- github - 在 Gatsby 上运行 SASS 不起作用
- c# - Xamarin 隐藏汉堡菜单栏
- python - GDAL算法GDALFillNodata()的C++实现
- java - java三元运算符内部+ intellij评估表达式
- python - TensorFlow tf.data.Dataset 和分桶
- angular - Angular2+ 测试用例显示 No provider for NgControl
- wordpress - WP_User_Query 仅拉入 1 个结果