简体   繁体   中英

Pass a 2d array to a function

I deal with graphs more often than not and find it difficult to pass the adjacency list to a function.

void myfunc(int ad[][])//proper way to receive it?
{
}

int main()
{
    int N;//number of vertices
    cin >> N;
    int ad[N][N];
    for(int i = 0; i<N; i++)
        for(int j = 0;j<N;j++)
            cin >> ad[i][j];
    myfunc(ad); //proper way to pass it?
    return 0;
}

Sorry if this is a noob question but I found people passing 2d arrays which had fixed and known dimensions only. No idea how to do this.

Variable length array (VLA) is not standard in C++.

Use std::vector instead:

void myfunc(const std::vector<std::vector<int>>& ad)
{
}

int main()
{
    int N;//number of vertices
    cin >> N;
    std::vector<std::vector<int>> ad(N, std::vector<int>(N));
    for(int i = 0; i<N; i++)
        for(int j = 0;j<N;j++)
            cin >> ad[i][j];
    myfunc(ad);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM