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

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

Do jagged arrays exist in C/C++?

c++cjagged-arrays

提问by unknown

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

在 C 或 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

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

回答by Cromulent

In C I would use an array of pointers.

在 CI 中会使用一个指针数组。

For instance:

例如:

int *jagged[5];

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

etc etc.

等等等等

回答by rampion

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 };

回答by rampion

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.

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

回答by Gabriele D'Antona

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

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);

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

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

回答by Faisal Vali

In C99 you can do the following:

在 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} };  

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 ;)

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

回答by John Bode

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

出现错误的原因是您必须至少为外部维度指定边界;IE

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.

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

What you cando 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 的指针数组;这样每个元素都可以指向不同大小的整数数组:

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 *).

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

回答by moooeeeep

With C++11 initializer lists thiscan be written more compactly:

随着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";
    }
}

The output is:

输出是:

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

For reference:

以供参考:

回答by robespierre

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

您还可以使用 c 中的复合文字来初始化一个真正的锯齿状数组,该数组在内存中是连续的,如下所示:

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

This will be laid out contiguously in memory.

这将在内存中连续排列。

回答by WSW

//
//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;
}