如何在 C++ 中调整数组大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3749660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to resize array in C++?
提问by devnull
I need to do the equivalent of the following C# code in C++
我需要在 C++ 中执行以下 C# 代码的等效操作
Array.Resize(ref A, A.Length - 1);
How to achieve this in C++?
如何在 C++ 中实现这一点?
回答by Kirill Muzykov
You cannot resize array, you can only allocate new one (with a bigger size) and copy old array's contents.
If you don't want to use std::vector
(for some reason) here is the code to it:
您无法调整数组大小,只能分配新数组(更大的大小)并复制旧数组的内容。如果你不想使用std::vector
(出于某种原因)这里是它的代码:
int size = 10;
int* arr = new int[size];
void resize() {
size_t newSize = size * 2;
int* newArr = new int[newSize];
memcpy( newArr, arr, size * sizeof(int) );
size = newSize;
delete [] arr;
arr = newArr;
}
code is from here http://www.cplusplus.com/forum/general/11111/.
回答by sbi
The size of an array is static in C++. You cannot dynamically resize it. That's what std::vector
is for:
数组的大小在 C++ 中是静态的。您不能动态调整它的大小。这std::vector
就是为了:
std::vector<int> v; // size of the vector starts at 0
v.push_back(10); // v now has 1 element
v.push_back(20); // v now has 2 elements
v.push_back(30); // v now has 3 elements
v.pop_back(); // removes the 30 and resizes v to 2
v.resize(v.size() - 1); // resizes v to 1
回答by Alam
- Use
std::vector
or - Write your own method. Allocate chunk of memory using new. with that memory you can expand till the limit of memory chunk.
- 使用
std::vector
或 - 编写自己的方法。使用 new 分配内存块。使用该内存,您可以扩展到内存块的限制。
回答by paxdiablo
Raw arrays aren't resizable in C++.
原始数组在 C++ 中不可调整大小。
You should be using something like a Vectorclass which does allow resizing..
您应该使用类似Vector类的东西,它确实允许调整大小..
std::vector
allows you to resize it as well as allowing dynamic resizing when you add elements (often making the manual resizing unnecessary for adding).
std::vector
允许您在添加元素时调整它的大小以及允许动态调整大小(通常使手动调整大小不需要添加)。
回答by rics
You cannot do that, see this question's answers. You may use std:vector instead.
您不能这样做,请参阅此问题的答案。您可以使用 std:vector 代替。