C/C++ 中是否存在锯齿状数组?

发布于 2024-07-26 08:07:35 字数 204 浏览 3 评论 0原文

C 或 C++ 中是否有锯齿数组之类的东西?

当我编译这个时:

int jagged[][] = { {0,1}, {1,2,3} };

我收到此错误:

错误:将“锯齿形”声明为多维数组必须具有除第一个维度之外的所有维度的边界

Is there such a thing as a jagged array in C or C++?

When I compile this:

int jagged[][] = { {0,1}, {1,2,3} };

I get this error:

error: declaration of `jagged' as multidimensional array must have bounds for all dimensions except the first

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

兮颜 2024-08-02 08:07:35

在 CI 中会使用指针数组。

例如:

int *jagged[5];

jagged[0] = malloc(sizeof(int) * 10);
jagged[1] = malloc(sizeof(int) * 3);

等等等等。

In C I would use an array of pointers.

For instance:

int *jagged[5];

jagged[0] = malloc(sizeof(int) * 10);
jagged[1] = malloc(sizeof(int) * 3);

etc etc.

拥有 2024-08-02 08:07:35

有很多方法可以做到这一点。 这是另一种方法:

int jagged_row0[] = {0,1};
int jagged_row1[] = {1,2,3};
int *jagged[] = { jagged_row0, jagged_row1 };

There's a bunch of ways to do it. Here's another way:

int jagged_row0[] = {0,1};
int jagged_row1[] = {1,2,3};
int *jagged[] = { jagged_row0, jagged_row1 };
冰魂雪魄 2024-08-02 08:07:35

如果你只是想初始化它,你可以说:

int jagged[][3] = { {0,1}, {1,2,3} };

但数组仍然具有[2][3]的形状。 如果您想要一个真正的锯齿状数组,则必须动态创建它。 如果您这样做,并且使用 C++,则应该使用 std::vector,正如 friol 建议的那样。

If you just want to initialise it, you can say:

int jagged[][3] = { {0,1}, {1,2,3} };

but the array will still have the shape [2][3]. If you want a true jagged array, you will have to create it dynamically. And if you do that, and are using C++, you should use a std::vector, as friol suggests.

生生不灭 2024-08-02 08:07:35

C++ 中(未编译,可能有更紧凑的语法):

std::vector<std::vector<int> > myArray;

myArray.push_back(std::vector<int>());
myArray.push_back(std::vector<int>());

myArray[0].push_back(0);
myArray[0].push_back(1);

myArray[1].push_back(1);
myArray[1].push_back(2);
myArray[1].push_back(3);

所以现在您可以使用 myArray[0][0] 等访问元素。

In C++ (not compiled, and probably there's a more compact syntax):

std::vector<std::vector<int> > myArray;

myArray.push_back(std::vector<int>());
myArray.push_back(std::vector<int>());

myArray[0].push_back(0);
myArray[0].push_back(1);

myArray[1].push_back(1);
myArray[1].push_back(2);
myArray[1].push_back(3);

So now you can access the elements with, for example, myArray[0][0], etc.

浪推晚风 2024-08-02 08:07:35

使用 C++11 初始值设定项列表 可以更紧凑地编写:

#include <vector>
#include <iostream>

int main() {
    // declare and initialize array
    std::vector<std::vector<int>> arr = {{1,2,3}, {4,5}};
    // print content of array
    for (auto row : arr) {
        for (auto col : row)
            std::cout << col << " ";
        std::cout << "\n";
    }
}

输出为:

$ g++ test.cc -std=c++11 && ./a.out
1 2 3 
4 5 

供参考:

With C++11 initializer lists this can be written more compactly:

#include <vector>
#include <iostream>

int main() {
    // declare and initialize array
    std::vector<std::vector<int>> arr = {{1,2,3}, {4,5}};
    // print content of array
    for (auto row : arr) {
        for (auto col : row)
            std::cout << col << " ";
        std::cout << "\n";
    }
}

The output is:

$ g++ test.cc -std=c++11 && ./a.out
1 2 3 
4 5 

For reference:

凉薄对峙 2024-08-02 08:07:35

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

int jagged_row0[] = {0,1};
int jagged_row1[] = {1,2,3};

int (*jagged[])[] = { &jagged_row0, &jagged_row1 }; // note the ampersand

// also since compound literals are lvalues ...
int (*jagged2[])[] = { &(int[]){0,1}, &(int[]){1,2,3} };  

这里唯一的区别(与 Rampion 的答案相比)是数组不会衰减为指针,并且必须通过另一级间接访问单个数组 - (例如 *jagged [0] - 并且必须记录每行的大小 - 即 sizeof(*jagged[0]) 将无法编译) - 但它们在骨头上呈锯齿状;)

In C99 you can do the following:

int jagged_row0[] = {0,1};
int jagged_row1[] = {1,2,3};

int (*jagged[])[] = { &jagged_row0, &jagged_row1 }; // note the ampersand

// also since compound literals are lvalues ...
int (*jagged2[])[] = { &(int[]){0,1}, &(int[]){1,2,3} };  

The only difference here (as compared to rampion's answer) is that the arrays don't decay to pointers and one has to access the individual arrays via another level of indirection - (e.g. *jagged[0] - and the size of each row has to be recorded - i.e. sizeof(*jagged[0]) will not compile) - but they're jagged-appearing to the bone ;)

瞄了个咪的 2024-08-02 08:07:35

出现错误的原因是您必须至少指定外部尺寸的边界; 即,

int jagged[][3] = {{0,1},{1,2,3}};

不能让 jagged[0] 为 2 元素 int 数组,而 jagged[1] 为 3 元素 int 数组; N 元素数组与 M 元素数组(其中 N != M)是不同的类型,并且数组的所有元素必须是相同的类型。

可以做的就是上面其他人的建议,并将 jagged 创建为指向 int 的指针数组; 这样每个元素都可以指向不同大小的整数数组:

int row0[] = {0,1};
int row1[] = {1,2,3};
int *jagged[] = {row0, row1};

即使 row0 和 row1 是不同类型(2 元素与 3 元素 int 数组),在初始化程序的上下文中,它们都隐式转换为相同类型(整数*)。

The reason you got the error is that you must specify the bounds for at least the outer dimension; i.e.

int jagged[][3] = {{0,1},{1,2,3}};

You cannot have jagged[0] be a 2-element array of int and jagged[1] be a 3-element array of int; an N-element array is a different type from an M-element array (where N != M), and all elements of an array must be the same type.

What you can do is what the others have suggested above and create jagged as an array of pointers to int; that way each element can point to integer arrays of different sizes:

int row0[] = {0,1};
int row1[] = {1,2,3};
int *jagged[] = {row0, row1};

Even though row0 and row1 are different types (2-element vs. 3-element arrays of int), in the context of the initializer they are both implicitly converted to the same type (int *).

○愚か者の日 2024-08-02 08:07:35

您还可以使用 c 中的复合文字来初始化在内存中连续的真正交错数组,如下所示:

int (*arr[]) = { (int []) {0, 1}, (int []){ 2, 3, 4}, (int []){5, 6, 7, 8} }

这将在内存中连续布置。

You can also use the compound literals in c to initialize a truly jagged array which is contiguous in memory as follows:

int (*arr[]) = { (int []) {0, 1}, (int []){ 2, 3, 4}, (int []){5, 6, 7, 8} }

This will be laid out contiguously in memory.

妥活 2024-08-02 08:07:35

通过在 cpp 中使用动态分配,我们可以创建锯齿状数组。

例如:

#include<iostream>
using namespace std;
    
int main(){
    int n;
    cout<<"Enter n:";
    cin>>n;
    
    cout<<"Enter elements:"; 
    int **p = new int *[n];
    
    for(int i=0;i<n;i++){
        p[i] = new int[i+1];
        for(int j=0;j<(i+1);j++){
            cin>>p[i][j];
        }
    } 
    
    cout<<"Jagged Array:"<<endl; 
    for(int i=0;i<n;i++){
        for(int j=0;j<(i+1);j++){
            cout<<p[i][j]<<" ";           
        }
        cout<<endl;
    }
    
    for(int i=0;i<n;i++){
        delete []p[i];
    }
    delete []p;
}
    

对于 n=3,我们创建了一个如下所示的锯齿状数组:

  • 输入 n: 3

输入元素:
1
1 2
1 2 3
锯齿状阵列:
1
1 2
1 2 3

By using dynamic allocation in cpp we can create jagged arrays.

For example:

#include<iostream>
using namespace std;
    
int main(){
    int n;
    cout<<"Enter n:";
    cin>>n;
    
    cout<<"Enter elements:"; 
    int **p = new int *[n];
    
    for(int i=0;i<n;i++){
        p[i] = new int[i+1];
        for(int j=0;j<(i+1);j++){
            cin>>p[i][j];
        }
    } 
    
    cout<<"Jagged Array:"<<endl; 
    for(int i=0;i<n;i++){
        for(int j=0;j<(i+1);j++){
            cout<<p[i][j]<<" ";           
        }
        cout<<endl;
    }
    
    for(int i=0;i<n;i++){
        delete []p[i];
    }
    delete []p;
}
    

For n=3, we have created a jagged array in the following look:

  • Enter n: 3

Enter elements:
1
1 2
1 2 3
Jagged Array:
1
1 2
1 2 3

谁的新欢旧爱 2024-08-02 08:07:35
//
//jaggedArrays.cpp
//
//program to implement jagged arrays in c++
//
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
    int rows, i, j;
    cout << endl << "Enter no of rows : ";
    cin >> rows;

    int columnsSizeOfEachRow[rows];

    cout << endl;
    for( i = 0 ; i < rows ; i++ )
    {
        cout << "Enter column size for row no " << i + 1 << " : ";
        cin >> columnsSizeOfEachRow[i];
    }
    
    int *jaggedArray[rows];
    for (i = 0 ; i < rows ; i++)
        jaggedArray[i] = new int[columnsSizeOfEachRow[i]];
    
    cout << endl;
    for(i = 0 ; i < rows ; i++)
    {
        for ( j = 0 ; j < columnsSizeOfEachRow[i] ;j++)
        {
            cout << "Array[" << i + 1 << "][" << j + 1 << "] << ";
            cin >> jaggedArray[i][j];
        }
        cout << endl;
    }

    cout << endl << endl << "Jagged array is as follows : " << endl;
    for( i = 0 ; i < rows ; i++)
    {
        for ( j = 0 ; j < columnsSizeOfEachRow[i] ;j++)
            cout << setw(3) <<jaggedArray[i][j] << " ";
        cout << endl;
    }    

    return 0;
}
//
//jaggedArrays.cpp
//
//program to implement jagged arrays in c++
//
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
    int rows, i, j;
    cout << endl << "Enter no of rows : ";
    cin >> rows;

    int columnsSizeOfEachRow[rows];

    cout << endl;
    for( i = 0 ; i < rows ; i++ )
    {
        cout << "Enter column size for row no " << i + 1 << " : ";
        cin >> columnsSizeOfEachRow[i];
    }
    
    int *jaggedArray[rows];
    for (i = 0 ; i < rows ; i++)
        jaggedArray[i] = new int[columnsSizeOfEachRow[i]];
    
    cout << endl;
    for(i = 0 ; i < rows ; i++)
    {
        for ( j = 0 ; j < columnsSizeOfEachRow[i] ;j++)
        {
            cout << "Array[" << i + 1 << "][" << j + 1 << "] << ";
            cin >> jaggedArray[i][j];
        }
        cout << endl;
    }

    cout << endl << endl << "Jagged array is as follows : " << endl;
    for( i = 0 ; i < rows ; i++)
    {
        for ( j = 0 ; j < columnsSizeOfEachRow[i] ;j++)
            cout << setw(3) <<jaggedArray[i][j] << " ";
        cout << endl;
    }    

    return 0;
}
初相遇 2024-08-02 08:07:35

交错数组确实存在于 c++/c 中,但语法相当复杂,你必须处理很多事情。

There are two types of jagged arrays in c++.
1) STATIC JAGGED ARRAY(A 2d array in which the size will be a constant number and there will be different number of columns in each row).

2) DYNAMIC JAGGED ARRAY(A 2d array in which the size will be any number taken from user and there will be different number of columns in each row)


1) 实现静态锯齿数组的步骤

  • 使用数组和指针
    • 1) 声明一维数组,其中包含您需要的行数
    • 2) 每个数组的大小(数组)对于行中的元素)将是行中的列数(或元素)
    • 3) 声明一个一维指针数组,用于保存箭头的地址
    • 4) 一维数组的大小是锯齿状数组中所需的行数
    #include<iostream>
    #include<string>
    using namespace std;
    int main()
    {
        int row0[4] = { 1,2,3,4 };
        int row1[2] = { 5,6 };
        int* jagged[2] = { row0,row1 };
        int Size[2] = { 4,2 }, k = 0;
        for (int i = 0; i < 2; i++)
        {
            int* ptr = jagged[i];
            for (int j = 0; j < Size[k]; j++)
            {
                cout << *ptr << "";
                ptr++;
            }
            cout << endl;
            k++;
            jagged[i]++;
        }
        return 0;
    }
    

    输出如下


    1234
    56



    1) 实现动态锯齿状数组的步骤

  • 使用指针数组
    • 1) 声明一个指针数组(锯齿状数组)
    • 2) 该数组的大小将是锯齿状数组中所需的行数
    • 3) 为数组中的每个指针分配与您想要的元素数量相同的内存想要在这一排。
    #include<iostream>
    #include<string>
    using namespace std;
    int main()
    {
        //2 rows
        int* jagged[2];
    
        //Allocate memeory for the elements in the row 0
        jagged[0] = new int[1];
    
        //Allocate memory for the elements in row 1
        jagged[1] = new int[5];
    
        //Array to hold the size of each row
        int Size[2] = { 1,5 },k = 0, number = 100;
    
        //User enters the numbers
        for (int i = 0; i < 2; i++)
        {
            int* p = jagged[i];
    
            for (int j = 0; j < Size[k]; j++)
            {
                *p = number++;
    
                //move the pointer
                p++;
            }
            k++;
        }
        k = 0;
    
        //Display elements in Jagged array
        for (int i = 0; i < 2; i++)
        {
            int* q = jagged[i];
            for (int j = 0; j < Size[k]; j++)
            {
                cout << *q << "";
                //move the pointer to the next element
                q++;
            }
            cout << endl;
            k++;
            //move the pointer to the next row
            jagged[i]++;
        }
        delete[] jagged[0];
        delete[] jagged[1];
        return 0;
    }
    

    The output is as follows


    100
    101102103104105


    The jagged arrays do exist in c++/c but the syntax is quite complex and you have to handle many things.

    There are two types of jagged arrays in c++.
    1) STATIC JAGGED ARRAY(A 2d array in which the size will be a constant number and there will be different number of columns in each row).

    2) DYNAMIC JAGGED ARRAY(A 2d array in which the size will be any number taken from user and there will be different number of columns in each row)


    1)STEPS OF IMPLEMENTING STATIC JAGGED ARRAY

  • Using array and a pointer
    • 1) Declare 1-D arrays with the number of rows you will need
    • 2) The size of each array(array for the elements in the row) will be the number of columns (or elements) in the row
    • 3) Declare a 1-D array of pointers that will hold the addresses of the arrows
    • 4) The size of the 1-D array is the number of rows you want in the jagged array
    #include<iostream>
    #include<string>
    using namespace std;
    int main()
    {
        int row0[4] = { 1,2,3,4 };
        int row1[2] = { 5,6 };
        int* jagged[2] = { row0,row1 };
        int Size[2] = { 4,2 }, k = 0;
        for (int i = 0; i < 2; i++)
        {
            int* ptr = jagged[i];
            for (int j = 0; j < Size[k]; j++)
            {
                cout << *ptr << "";
                ptr++;
            }
            cout << endl;
            k++;
            jagged[i]++;
        }
        return 0;
    }
    

    The output is as follows


    1234
    56



    1)STEPS OF IMPLEMENTING DYNAMIC JAGGED ARRAY

  • Using an array of pointer
    • 1) Declare an array of pointers(jagged array)
    • 2) The size of this array will be the number of rows required in the jagged array
    • 3) For each pointer in the array allocate memory for the number of elements you want in this row.
    #include<iostream>
    #include<string>
    using namespace std;
    int main()
    {
        //2 rows
        int* jagged[2];
    
        //Allocate memeory for the elements in the row 0
        jagged[0] = new int[1];
    
        //Allocate memory for the elements in row 1
        jagged[1] = new int[5];
    
        //Array to hold the size of each row
        int Size[2] = { 1,5 },k = 0, number = 100;
    
        //User enters the numbers
        for (int i = 0; i < 2; i++)
        {
            int* p = jagged[i];
    
            for (int j = 0; j < Size[k]; j++)
            {
                *p = number++;
    
                //move the pointer
                p++;
            }
            k++;
        }
        k = 0;
    
        //Display elements in Jagged array
        for (int i = 0; i < 2; i++)
        {
            int* q = jagged[i];
            for (int j = 0; j < Size[k]; j++)
            {
                cout << *q << "";
                //move the pointer to the next element
                q++;
            }
            cout << endl;
            k++;
            //move the pointer to the next row
            jagged[i]++;
        }
        delete[] jagged[0];
        delete[] jagged[1];
        return 0;
    }
    

    The output is as follows


    100
    101102103104105


    謸气贵蔟 2024-08-02 08:07:35

    不,C 和 C++ 中都没有锯齿状的多维数组。 您可以创建各种结构,以一定的内存成本执行类似的功能(例如 指向数组的指针数组 ),但不是实际的 C 风格多维数组。

    原因是C风格的数组,无论有多少维,占用连续的内存区域< /a> 没有元数据。 所以,就记忆而言,它们都是单维的。 这只是指针算术的巧妙之处(将指针跨过行的大小)您可以使用额外维度的功能。 串行布局的交错数组具有不同的行大小,因此它不能通过常数值跨步,因此根据数据大小需要额外的存储空间,因此无法在 C 类型系统中表达。

    当您考虑指针多维数组衰减到什么时,它会变得更清楚: 数组到指针衰减以及将多维数组传递给函数

    这就是为什么您会看到错误消息必须对除第一个维度之外的所有维度都有边界,因为除了第一个维度之外的所有维度都是跨过数组。

    No, there are no jagged multidimensional arrays in C nor C++. You can create various constructs that perform similar function at some memory cost (like array of pointers to arrays), but not an actual C-style multidimensional array.

    The reason is that C-style arrays, no matter how many dimensions, occupy contiguous memory area with no metadata. So, memory-wise, they're all single-dimensional. It's only the cleverness of pointer arithmetic (striding the pointer by the size of a row) that gives you the functionality of extra dimensions. A jagged array laid out serially has different row sizes, so it cannot be strode by a constant value, so it requires additional storage depending on data size, thus is impossible to express in C type system.

    It becomes clearer when you consider to what pointer multidimensional array decay to: Array to pointer decay and passing multidimensional arrays to functions

    And that's why you see the error message must have bounds for all dimensions except the first, because all dimensions except the first are necessary to stride the array.

    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文