【问题标题】:initialize array of pointer and matrix初始化指针和矩阵数组
【发布时间】:2021-12-10 23:03:11
【问题描述】:

我想初始化指针数组。(不是普通数组)但这不起作用。

int* arr = new int [5];
arr = {1,2,3,4,5};

我也不想这样:(因为如果尺寸改变我必须改变代码)

arr[0] = 1; arr[1] = 2; ...

有没有简单的方法来做到这一点?矩阵呢?

int** mat = ...
mat = { {1,2} , {3,4} }

而且我也不希望这样初始化:(因为当我想将矩阵传递给函数时有一些限制(例如:如果大小改变,我必须改变函数定义)

int mat[2][2] = { {1,2} , {3,4} };

【问题讨论】:

  • 如果大小在编译时已知而不是使用原始数组,为什么不std::vector<int> arr = {1,2,3,4,5}std::array<std::array<int, 2>, 2>
  • 您可以使用模板函数自动推断数组大小。如template<size_t R, size_t C> void f(std::array<std::array<int, C>, R> const&) { ... }
  • @CoryKramer 1-问题限制 2-我想知道有没有办法通过使用原始数组来做到这一点:)。

标签: c++ arrays pointers matrix initialization


【解决方案1】:

你可以写例子

int* arr = new int [5] { 1, 2, 3, 4, 5 };

或者例如你可以使用算法std::iota like

int* arr = new int [5];
std::iota( arr, arr + 5, 1 );

或其他一些算法,例如std::fillstd::generate

如果数组将被重新分配,那么在这种情况下使用标准容器std::vector<int> 会更好。

(例如:如果尺寸改变,我必须改变功能定义))

您可以将函数定义为模板函数,其中数组的大小将是模板非类型参数。

【讨论】:

  • 就是这样。谢谢!
【解决方案2】:

如果您真的想要自己动态创建一个数组,那么按照莫斯科的@Vlad 的建议进行操作:

int* arr = new int [5] {1, 2, 3, 4, 5};

或:

int* arr = new int [5];
std::iota( arr, arr + 5, 1 ); // also std::fill or std::generate

但是,在 99% 的情况下,使用 std::vector 几乎在各个方面都更好。

您的代码如下所示:

std::vector<int> arr{1, 2, 3, 4, 5};
// if you know the size of the array at runtime, then do this
arr.resize(5 /* size of the array at runtime */)

更好的是,如果您在编译时知道数组的大小,那么std::array 是您最好的朋友。

std::array&lt;int, 5 /* size of the array at compile time */&gt; arr{1, 2, 3, 4, 5};

【讨论】:

    【解决方案3】:

    这是一个使用 std::make_unique 来避免新建/删除的示例。 但是,如您所见,必须手动维护数组大小。 所以你还是最好使用 std::vector 或 std::array

    #include <algorithm>
    #include <iostream>
    #include <memory>
    
    // allocate with make_unqiue and initialize from list
    template<typename type_t, std::size_t N>
    auto make_array(const type_t (&values)[N])
    {
        std::unique_ptr<type_t[]> array_ptr = std::make_unique<type_t[]>(N);
        for (std::size_t n = 0; n < N; ++n) array_ptr[n] = values[n];
        return array_ptr;
    }
    
    int main() 
    {
        auto array_ptr = make_array({ 1,2,3,4,5 });
    
        for (std::size_t n = 0; n < 5; ++n)
        {
            std::cout << array_ptr[n] << " ";
        }
    
        // std::unique_ptr will take care of deleting the memory
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多