c++ - C++ 问题,其中分配给变量的值正在更改,即使它尚未修改
问题描述
请帮助我解决这个奇怪的问题,其中输入值为 4(即 n = 4),并且在 for 循环之后,相同的值显示为 2,但为什么呢?它没有在任何地方使用(AFAIK),也不应该改变(我对此一无所知)。
HackerRank上的原始问题。
我的代码>>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
int arr[n];
cin >> n; // input given from stdin is 4
cout << n << "\n"; // outputs 4
for(int i=0; i<n; i++){
scanf("%d",&arr[i]);
}
cout << n << "\n"; // outputs 2 (but why?)
for(int i=n-1; i>=0; i--){
printf("%d ",arr[i]); // if it were n = 4, then i will go from 3 to 0, but it goes from 1 to 0 (as n=2, but again, why?)
}
return 0;
}
感谢您的任何帮助!
解决方案
int n;
int arr[n]; // <<<<<< I magically know what n will be after the user types it!
cin >> n; // input given from stdin is 4
首先,这在 C++ 中甚至是不合法的。作为支持 C 风格 VLA 的 gcc 扩展,看到数组声明时 n 的值是多少?你还没读过!!
相反,使用:
int n;
cin >> n;
std::vector arr(n);
尽管这仍然不是“C++ 方式”,因为您要预先定义整个集合,然后依次分配给每个元素;而不是将每个元素添加到集合中。这不是什么大问题,int
但更一般地说,您不希望集合中未使用的项目死亡;相反,它们根本不存在。
std::vector arr; // don't pre-allocate any size
for(int i=0; i<n; i++){
int val;
scanf("%d",&val); //<<< uhhhhhh. you know about `cin` why this?
arr.push_back(val);
}
推荐阅读
- flask - 为什么我的 Flask 后端在 Heroku 上不稳定?
- java - 当我们开始一个新视频时,如何停止当前的 Youtube 视频?
- python - 在下标中访问snakemake变量
- java - Java和Python中基于经纬度的唯一数字生成
- vba - 从 Outlook 会议项目复制收件人姓名
- python - 将字节串作为参数传递时出现问题
- gnuradio - 为什么我在 GNU Radio 的 VCO 块中只得到零?
- python - update UI component from model
- python - 按字典的列表索引对字典列表进行排序
- r - 如何为R中的每一行添加一个新值