你可以调整初始化后的C ++数组? [英] Can you resize a C++ array after initialization?

查看:128
本文介绍了你可以调整初始化后的C ++数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习编程,和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];
    }

我被分配(我不上课 - 刚刚与几个朋友帮助我学习)合并排序算法,该算法解释,但没有实现。我想改写这个所以它会为奇数和偶数工作。我尝试添加该code:

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 ::矢量而不是阵列。

If you need a "resizable array", you'll want to use std::vector instead of an array.

这篇关于你可以调整初始化后的C ++数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆