您如何将特定值设置为动态数组

How do you set specific values to a dynamic array?

本文关键字:设置 动态 数组      更新时间:2023-10-16

显然我正在误解这一点,但是我试图将特定的数字设置为动态内存数组。

#include <iostream>
#include <cstdlib>
using namespace std;
int main () {
    int *arr = new int [4][5]
    {{3, 6, 9, 23, 16}, 
    {24, 12, 9, 13, 5},
    {37, 19, 43, 17, 11},
    {71, 32, 8, 4, 7}};
    cout<< arr [1][3]<< endl<< endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl; 
    delete x;
    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return;
}

c 对多维数组的支持是通过库(例如Boost)完成的。如果没有类,它实际上只能理解1D数组,尤其是当您使用指针时,C/C 确实将其视为指向数组的第一个元素的指针。要使您的示例在没有类的情况下工作,您需要定义一种容纳一行的类型,然后创建该类型的数组,您可以在显示时分配值。

#include <iostream>
#include <cstdlib>
using namespace std;
int main () {
    typedef int row_t[5];
    row_t *arr = new row_t[4] {{3, 6, 9, 23, 16}, 
    {24, 12, 9, 13, 5},
    {37, 19, 43, 17, 11},
    {71, 32, 8, 4, 7}};
    cout<< arr[1][3] << endl<< endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl; 
    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return 0;
}

另外,您可以将2D数组投射到1D数组上:

#include <iostream>
#include <cstdlib>
using namespace std;
int main () {
    int *arr = new int[20] {3, 6, 9, 23, 16, 
    24, 12, 9, 13, 5,
    37, 19, 43, 17, 11,
    71, 32, 8, 4, 7};
    cout<< arr[5*1+3] << endl<< endl;
    int *x = new int;
    *x = arr [5*2+1];
    cout<< x<< endl;
    cout<< *x<< endl << endl; 
    *x = arr [5*0+3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return 0;
}

使用动态数据获得2D索引,使用boost :: multi_array

#include <iostream>
#include <boost/multi_array.hpp>
using namespace std;
int main () {
    boost::multi_array< int, 2 >arr(boost::extents[4][5]);
    int tmp[] { 3, 6, 9, 23, 16, 
      24, 12, 9, 13, 5,
      37, 19, 43, 17, 11,
      71, 32, 8, 4, 7 };
    arr = boost::multi_array_ref< int, 2 >( &tmp[0], boost::extents[4][5] );
    cout<< arr [1][3]<< endl << endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl; 
    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    // delete [] arr;
    return 0;
}

使用操作员新的是棘手。您的程序在使用新和删除方面存在许多错误。动态阵列的标准实现可以隐藏所有棘手的棘手并自行清理,即std :: vector。另外,避免使用"使用命名空间std";您可以以这种方式感到困惑的名字冲突。

效果很好 -

#include <iostream>
#include <cstdlib>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main () {
    vector<vector<int>> arr 
    { { 3, 6, 9, 23, 16 },
    { 24, 12, 9, 13, 5 },
    { 37, 19, 43, 17, 11 },
    { 71, 32, 8, 4, 7 } };
    cout<< arr[1][3]<< endl<< endl;
    int x = arr[2][1];
    cout<< x<<  endl;
    cout<< x<< endl << endl;
    x = arr[0][3];
    cout<< x<< endl;
    return 0;
}

P.S。您使用ARR的方式没有什么动态的。您可以这样声明:

int arr[4][5] 
{ { 3, 6, 9, 23, 16 },
{ 24, 12, 9, 13, 5 },
{ 37, 19, 43, 17, 11 },
{ 71, 32, 8, 4, 7 } };