C++ 定义数组,然后更改其大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3851181/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:53:41  来源:igfitidea点击:

Define array, then change its size

c++arrays

提问by user69514

I come from a java background and there's something I could do in Java that I need to do in C++, but I'm not sure how to do it.

我来自 Java 背景,我可以用 Java 做一些我需要用 C++ 做的事情,但我不知道该怎么做。

I need to declare an array, but at the moment I don't know the size. Once I know the size, then I set the size of the array. I java I would just do something like:

我需要声明一个数组,但目前我不知道大小。一旦我知道大小,然后我设置数组的大小。我 java 我只会做类似的事情:

int [] array;

then

然后

array = new int[someSize];

How do I do this in C++?

我如何在 C++ 中做到这一点?

回答by SingleNegationElimination

you want to use std::vectorin most cases.

你想std::vector在大多数情况下使用。

std::vector<int> array;

array.resize(someSize);

But if you insist on using new, then you have do to a bit more work than you do in Java.

但是,如果您坚持使用new,那么您必须比在 Java 中做更多的工作。

int *array;
array = new int[someSize];

// then, later when you're done with array

delete [] array;

No c++ runtimes come with garbage collection by default, so the delete[]is required to avoid leaking memory. You can get the best of both worlds using a smart pointer type, but really, just use std::vector.

默认情况下,没有 C++ 运行时带有垃圾收集,因此delete[]需要避免内存泄漏。您可以使用智能指针类型获得两全其美,但实际上,只需使用std::vector.

回答by codaddict

In C++ you can do:

在 C++ 中,您可以执行以下操作:

int *array; // declare a pointer of type int.
array = new int[someSize]; // dynamically allocate memory using new

and once you are done using the memory..de-allocate it using delete as:

一旦你使用完内存..使用删除来取消分配它:

delete[]array;

回答by user225312

Best way would be for you to use a std::vector. It does all you want and is easy to use and learn. Also, since this is C++, you should use a vectorinstead of an array. Hereis an excellent reason as to why you should use a container class (a vector) instead of an array.

最好的方法是让你使用std::vector. 它可以满足您的所有需求,并且易于使用和学习。此外,由于这是 C++,您应该使用 avector而不是数组。这里有一个很好的理由说明为什么应该使用容器类(向量)而不是数组。

Vectors are dynamic in size and grow as you need them - just what you want.

矢量的大小是动态的,可以根据需要增长 - 正是您想要的。

回答by ssube

The exact answer:

确切答案:

char * array = new char[64]; // 64-byte array

// New array
delete[] array;
array = new char[64];

std::vectoris a much better choice in most cases, however. It does what you need without the manual delete and new commands.

std::vector然而,在大多数情况下是更好的选择。它无需手动删除和新命令即可完成您需要的操作。

回答by Martin T?rnwall

As others have mentioned, std::vectoris generally the way to go. The reason is that vector is very well understood, it's standardized across compilers and platforms, and above all it shields the programmer from the difficulties of manually managing memory. Moreover, vector elements are required to be allocated sequentially (i.e., vector elements A, B, C will appear in continuous memory in the same order as they were pushed into the vector). This should make the vector as cache-friendly as a regular dynamically allocated array.

正如其他人所提到的,std::vector通常是要走的路。原因是 vector 很好理解,它跨编译器和平台标准化,最重要的是它使程序员免受手动管理内存的困难。此外,向量元素需要按顺序分配(即,向量元素 A、B、C 将按照它们被推入向量的相同顺序出现在连续内存中)。这应该使向量像常规的动态分配数组一样对缓存友好。

While the same end result could definitely be accomplished by declaring a pointer to int and manually managing the memory, that would mean extra work:

虽然通过声明一个指向 int 的指针并手动管理内存肯定可以实现相同的最终结果,但这意味着额外的工作:

  1. Every time you need more memory, you must manually allocate it
  2. You must be very careful to delete any previously allocated memory before assigning a new value to the pointer, lest you'll be stuck with huge memory leaks
  3. Unlike std::vector, this approach is not RAII-friendly. Consider the following example:

    void function()
    {
        int* array = new int[32];
        char* somethingElse = new char[10];
        // Do something useful.... No returns here, just one code path.
        delete[] array;
        delete[] somethingElse;
    }
    
  1. 每次需要更多内存时,必须手动分配
  2. 在为指针分配新值之前,您必须非常小心地删除任何先前分配的内存,以免陷入巨大的内存泄漏
  3. 与 不同std::vector,这种方法不是RAII友好的。考虑以下示例:

    void function()
    {
        int* array = new int[32];
        char* somethingElse = new char[10];
        // Do something useful.... No returns here, just one code path.
        delete[] array;
        delete[] somethingElse;
    }
    

It looks safe and sound. But it isn't. What if, upon attempting to allocate 10 bytes for "somethingElse", the system runs out of memory? An exception of type std::bad_allocwill be thrown, which will start unwinding the stack looking for an exception handler, skippingthe delete statements at the end of the function. You have a memory leak. That is but one of many reasons to avoid manually managing memory in C++. To remedy this (if you really, really want to), the Boostlibrary provides a bunch of nice RAII wrappers, such as scoped_arrayand scoped_ptr.

它看起来安全无恙。但事实并非如此。如果在尝试为“somethingElse”分配 10 个字节时,系统内存不足怎么办?std::bad_alloc将抛出类型异常,它将开始展开堆栈以寻找异常处理程序,跳过函数末尾的删除语句。你有内存泄漏。这只是避免在 C++ 中手动管理内存的众多原因之一。为了解决这个问题(如果你真的,真的想要),Boost库提供了一堆很好的 RAII 包装器,比如scoped_arrayscoped_ptr

回答by SiegfriedDb

use std::array when size is known at compile time otherwise use std::vector

在编译时已知大小时使用 std::array 否则使用 std::vector

#include <array>
constexpr int someSize = 10;
std::array<int, someSize> array;

or

或者

#include <vector>
std::vector<int> array;  //size = 0
array.resize(someSize);  //size = someSize

回答by aib

Declare a pointer:

声明一个指针:

int * array;