动态数组 [英] Dynamic Arrays
问题描述
我刚开始学习C ++所以请原谅我这个简单的问题。我在做什么是从文件中读取的数字,然后试图将它们添加到一个数组。我的问题是你如何增加数组的大小?比如我想也许可以只是做:
I'm just starting to learn C++ so excuse me for this simple question. What I'm doing is reading in numbers from a file and then trying to add them to an array. My problem is how do you increase the size of the array? For example I thought might be able to just do:
#include <iostream>
using namespace std;
int main() {
double *x;
x = new double[1];
x[0]=5;
x = new double[1];
x[1]=6;
cout << x[0] << "," << x[1] << endl;
return 0;
}
但是,这显然只是覆盖值,5,我最初设置为x [0]和如此输出0,6。我将如何让这个它会输出5,6?
请注意,对于比如我包括我不想从一个在code读数混乱起来文件或code从用户获取数字。在实际应用中我不知道有多大的数组,我需要在编译的时候,所以请不要告诉我只是做一个数组包含两个元素,并将它们设置等于5,6分别。
感谢您的帮助。
But this obviously just overwrites the value, 5, that I initially set to x[0] and so outputs 0,6. How would I make it so that it would output 5,6?
Please realize that for the example I've included I didn't want to clutter it up with the code reading from a file or code to get numbers from a user. In the actual application I won't know how big of an array I need at compile time so please don't tell me to just make an array with two elements and set them equal to 5 and 6 respectively.
Thanks for your help.
推荐答案
您不想直接与阵列工作。考虑使用矢量
代替。然后,您可以拨打的push_back
函数添加东西到最后,它会自动调整向量为您服务。
You don't want to work with arrays directly. Consider using a vector
, instead. Then, you can call the push_back
function to add things to the end, and it will automatically resize the vector for you.
#include <iostream>
#include <vector>
int
main() {
double value;
std::vector<double> values;
// Read in values
while (std::cin >> value) {
values.push_back(value);
}
// Print them back out
for (std::size_t i(0), len(values.size()); i != len; ++i) {
std::cout << values[i];
}
}
这篇关于动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!