【问题标题】:How to create a dynamic array of integers如何创建一个动态整数数组
【发布时间】:2010-10-27 04:01:34
【问题描述】:

如何在 C++ 中使用 new 关键字创建一个动态整数数组?

【问题讨论】:

标签: c++


【解决方案1】:
int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

不要忘记delete 使用new 分配的每个数组。

【讨论】:

  • 8 年后,该评论可能会让初学者感到困惑@GManNickG,删除它怎么样(因为我想它是在 Jason Iverson 实际删除数组之前制作的)?
  • @gsamaras:我同意这令人困惑,但它仍然是正确的:您的代码不应该手动删除,您必须记住不要忘记。也就是说,使用了智能指针和其他容器。
  • @GManNickG 我认为您的评论可能不那么教条。代码是正确的,即使它并不理想。智能指针和容器几乎总是是更好的选择(尤其是在这样的初学者问题中),但并非总是“总是”。
  • 我同意@Spencer,代码没有错,很简单,完美的c++。您可能认为存在替代方案,称之为最佳实践等。但这个示例本身并没有错。
【解决方案2】:

自 C++11 起,new[]delete[] 有一个安全的替代方案,与std::vector 不同,它的开销为零:

std::unique_ptr<int[]> array(new int[size]);

在 C++14 中:

auto array = std::make_unique<int[]>(size);

以上都依赖同一个头文件,#include &lt;memory&gt;

【讨论】:

  • 我不知道是不是只有我,但 C++11 的语法看起来很糟糕。 C++14 看起来好多了。再说一次,自 C++11 之前我就没有跟上。记住所有这些新表达方式很难。
【解决方案3】:

您可能需要考虑使用标准模板库。它简单易用,而且您不必担心内存分配问题。

http://www.cplusplus.com/reference/stl/vector/vector/

int size = 5;                    // declare the size of the vector
vector<int> myvector(size, 0);   // create a vector to hold "size" int's
                                 // all initialized to zero
myvector[0] = 1234;              // assign values like a c++ array

【讨论】:

  • @Ed,问题中的限制似乎相当随意。 std::vector 与适当的构造函数工作得非常好,应该指出作为替代方案。有时人们问的问题很糟糕,这可能算作其中一种情况 - 它非常简短,并没有给出任何选择 new 的理由。
  • @Ed:没有理由使用new[] 代替std::vector
  • @baash:在 C++ 中,永远没有理由。如果您出于某种原因决定“删除标准库”,那么您将不再使用 C++ 进行编程。我的评论是针对 C++ 语言,而不是 C++-language-we-use-on-my-device。即便如此,您永远不需要手动 delete 任何东西。此外,std::vector 是一个动态数组,对链表没有任何作用。它只是一块内存的包装器。
  • @Montdidier:不。您仍然使用newdelete 来实现包装器。关键是你不管理资源使用它,你只做一个或另一个。
  • @Montdidier:让我们从声明开始:在 C++ 中,new[] 的所有实例都可以替换为std::vector。而且因为std::vector 正确地将资源管理与资源使用 (SBRM) 分开,我们应该这样做。
【解决方案4】:
int* array = new int[size];

【讨论】:

  • 它只是回答了问题。
  • @GManNickG 因为矢量可以更方便还是其他原因?因为我经常遇到需要使用数组而不是向量的 3rd 方函数。
  • @Lèsemajesté 没有理由不使用向量 — std::vector::data() 成员函数将在需要时返回底层原始数组。
  • @zenith:通常,您会使用operator&amp; 而不是data() 从向量中获取指针,但向量确实提供了与期望数组的函数兼容所需的连续性保证.
【解决方案5】:

一旦有关于动态数组的问题,您可能不仅希望创建具有可变大小的数组,还希望在运行时更改它的大小。这是memcpy 的示例,您也可以使用memcpy_sstd::copy。根据编译器,可能需要&lt;memory.h&gt;&lt;string.h&gt;。使用此函数时,您分配新的内存区域,将原始内存区域的值复制到它,然后释放它们。

//    create desired array dynamically
size_t length;
length = 100; //for example
int *array = new int[length];

//   now let's change is's size - e.g. add 50 new elements
size_t added = 50;
int *added_array = new int[added];

/*   
somehow set values to given arrays
*/ 

//    add elements to array
int* temp = new int[length + added];
memcpy(temp, array, length * sizeof(int));
memcpy(temp + length, added_array, added * sizeof(int));
delete[] array;
array = temp;

您可以使用常量 4 代替 sizeof(int)

【讨论】:

    【解决方案6】:

    使用new动态分配一些内存:

    int* array = new int[SIZE];
    

    【讨论】:

    • 您可能缺少冒号,或者没有将 SIZE 替换为 实际 尺寸。
    • 为什么要有分号?这不是一个完整的陈述。可能会有更多声明。如果包含在一个完整的程序中,这将按照 OP 的要求执行。
    【解决方案7】:

    上面的答案都适用于分配一维 int 数组。无论如何,我想补充一点,对于通常定义为 int[][] matrix = {{1,2}, {3,4}} 的多维数组,也可以这样做。

    关键是您将所有元素动态存储在一个数组中,并利用数组是内存中连续块的事实(请参阅here 以了解“块”的说明),这意味着您可以“切片” “穿越维度的你自己。您可以在下面看到一个二维数组的示例。

    您可以在 SO 上找到有关此主题的讨论 here

    /*Defining a 2d-matrix.*/
    struct Matrix {
    
        int rows, columns;
        int* matrix;
    
        Matrix(int rows, int columns) : rows(rows), columns(columns) {
            // Keep in mind that arrays cannot be generated during runtime
            // since the compiler needs to know the size to allocate in memory.
            // Thus, use dynamic memory and keep in mind to delete it!
    
            // This only uses a single array since "new" cannot create 
            // multidimensional arrays by default. Thus, everything is
            // written in a single memory-block and accessed via getElement().
            matrix = new int[columns * rows];
        }
    
        ~Matrix() {
            // Release the memory after destroying the Matrix-object
            delete matrix;
        }
    
        /*Access the element at position [r]ow and [c]olumn.*/
        int getElement(int r, int c) {
            // matrix[c][r] is rewritten as matrix[column + columns * rows] 
            // -> matrix <=> Single memory block
            return matrix[c + columns * r];
        }
    
        /*Set the element at position [r]ow and [c]olumn with given [val]ue.*/
        void setElement(int r, int c, int val) {
            matrix[c + columns * r] = val;
        }
    };
    

    填充此类Matrix-object 的示例如下:

        /*Initialize the matrix with the continuous numbers 0..N*/
        void Matrix::initDummyMatrix(){
            int counter = 0;
            for (int row = 0; row < rows; ++row) {
                for (int col = 0; col < columns; ++col) {
                    setElement(row, col, counter++);
                }
            }
        }
    

    【讨论】:

      【解决方案8】:
      #include <stdio.h>
      #include <cstring>
      #include <iostream>
      
      using namespace std;
      
      int main()
      {
      
          float arr[2095879];
          long k,i;
          char ch[100];
          k=0;
      
          do{
              cin>>ch;
              arr[k]=atof(ch);
              k++;
           }while(ch[0]=='0');
      
          cout<<"Array output"<<endl;
          for(i=0;i<k;i++){
              cout<<arr[i]<<endl;
          }
      
          return 0;
      }
      

      上述代码有效,可以定义的最大浮点数或整数数组大小为2095879,退出条件将为非零开头的输入数字

      【讨论】:

      • 这与一个动态数组的问题无关。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      相关资源
      最近更新 更多