我对 C++ 还很陌生,以前只使用过高级语言。
这是我的问题。只是为了尝试一些事情。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> ve(10);
for (unsigned int i; i < ve.size(); i++) {
ve[i] = i+1;
cout << ve[i] << endl;
}
cout << "Done filling vector. Now showing" << endl;
for (unsigned int y; y < ve.size(); y++) {
cout << ve[y] << endl;
}
cout << "We're done" << endl;
}
通过第一个“for”,我想用值填充 vector/数组并输出这些值。
第二个应该再次输出它们。然而这并没有发生。第一个 for 完成后,数组似乎是空的。
最佳答案
问题是您没有初始化迭代变量,这意味着它们获得了几乎随机的值(无论其所在位置的内存中发生了什么)。改为这样做:
for (unsigned int i = 0; i < ve.size(); i++) {
ve[i] = i+1;
cout << ve[i] << endl;
}
和
for (unsigned int y = 0; y < ve.size(); y++) {
cout << ve[y] << endl;
}
(注:区别在于初始化= 0
)
一些不相关的提示:
for
中声明的变量循环初始化子句是循环本地的,在循环外部无法访问它们。这意味着它们都可以被称为i
.std::endl
是“输出换行符”和“刷新缓冲区”的组合。除非您确实想要这两种操作,否则最好(从性能角度)仅输出\n
对于换行符。例如:cout << "We're done.\n";
对于测试程序来说这没问题,但一般建议不要这样做
using namespace std;
即使在源文件中(并且在头文件中这样做是非常危险的)。这很大程度上是风格问题,但有时您仍然可能会因名称冲突而受到影响。
关于c++ - for 中的数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20582522/