[英]Can I set for example array[n+k] = array[0]?
If I have this code: 如果我有此代码:
#include <iostream>
using namespace std;
int main()
{
int n, i;
cin >> n;
float array10[n];
cin >> array10[i];
}
How can I create array10[n+1]
and set the value of array10[0]
? 如何创建
array10[n+1]
并设置array10[0]
的值?
You can't. 你不能 In fact,
array10[n];
实际上,
array10[n];
isn't legal C++ (even if n
was initialized). 是不合法的C ++(即使
n
已初始化)。 Variable length arrays aren't a C++ feature. 可变长度数组不是C ++的功能。
Use std::vector
: 使用
std::vector
:
cin >> n;
std::vector<int> vec(n);
cin >> vec[i];
This code 这段代码
int n, i;
float array10[n];
is invalid because arrays in C+ require that their sizes would be constant expressions at compile time. 之所以无效,是因为C +中的数组要求其大小在编译时必须为常量表达式。 (Though some compilers have its own language extensions that allow to do that. But this code does not satisfy the C++ Standard) And if an array is defined you may not change its size.
(尽管某些编译器具有允许其执行此操作的语言扩展。但是此代码不符合C ++标准。)并且,如果定义了数组,则不能更改其大小。 If n would be a constant expression then you could write for example
如果n是一个常量表达式,那么您可以编写例如
const int n = 10;
float array[n];
float array1[n + 1]
Otherwise you have two approaches. 否则,您有两种方法。 Either you should use standard C++ container std::vector
您应该使用标准的C ++容器std :: vector
For example 例如
int n = 10;
std::vector<float> v( n );
and then you can resize this vector 然后您可以调整此向量的大小
v.resize( n + 1 );
Or you should dynamically allocate an array. 或者,您应该动态分配一个数组。 For example
例如
int n = 10;
float *array = new float[n];
and then reallocate it; 然后重新分配它;
float *tmp = new float[n + 1];
std::copy( array, array + n, tmp );
delete []array;
array = tmp;
You can do it by declaring array10 as a pointer 您可以通过将array10声明为指针来实现
cin >> n;
float* array10 = new float[n];
cin >> array10[i];
//do something
delete[] array10;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.