初始化后可以调整 C++ 数组的大小吗? [英] Can you resize a C++ array after initialization?
问题描述
我正在学习编程,C++ 是我的第一门语言.不要费心使用指针来向我展示 - 我还不理解它们,并且在我有更多空闲时间致力于此之前不会打扰.
I'm learning to program, and C++ is my first language. Don't bother using pointers to show me - I don't understand them yet, and won't bother until I have more free time to dedicate to this.
int mergeSort()
{
const int n = 9;
int originalarray[n] = {1, 3, 5, 7, 9, 2, 4, 6, 8};
const int halfelements = (sizeof(originalarray) / sizeof(int)) / 2;
int farray[halfelements];
int sarray[halfelements];
for (int i = 0; i < halfelements; i++) {
farray[i] = originalarray[i];
}
for (int i = halfelements, x = 0; i < (halfelements * 2); i++, x++) {
sarray[x] = originalarray[i];
}
我被分配了(我没有上课 - 只是和几个帮助我的朋友一起学习)一个合并排序算法,其中解释了算法,但没有解释实现.我想重写它,以便它适用于奇数和偶数整数.我尝试添加此代码:
I was assigned (I'm not taking classes - just learning with a few friends helping me out) a merge sort algorithm, with the algorithm explained but not the implementation. I want to rewrite this so it will work for both odd and even integers. I tried adding this code:
if ((n % 2) != 0) int farray[halfelements + 1];
这样我就可以使用相同的整数来迭代两个后续数组.sizeof(farray) 显示为 16 个字节,或 4 个整数.所以它没有调整大小.我想知道 - 是否可以在初始化后调整数组大小?
So that I could use the same integer to iterate over both subsequent arrays. A sizeof(farray) is showing to be 16 bytes, or 4 integers. So it isn't resizing. What I want to know - is it possible to resize arrays after they initialized?
我将如何实现向量?我不明白如何在循环中使用迭代器来迭代和复制值.
How would I implement a vector? I don't understand how to use iterators in a loop to iterate over and copy the values.
推荐答案
C++ 数组的大小是固定的.
C++ arrays are fixed in size.
如果你需要一个可调整大小的数组",你需要使用 std::vector 而不是数组.
If you need a "resizable array", you'll want to use std::vector instead of an array.
这篇关于初始化后可以调整 C++ 数组的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!