简体   繁体   中英

How to pair 2D array and integer in the output of the function?

I'm struggling to create multi-variable output from a function: I want to return 2D array sites(16x15) and the integer number N .

I tried:

  1. std::make_tuple here
  2. std:make_pair here

My problem is that I probably do not know how to define a 2D array in the declaration of the function std::pair <int [][] ,int> correctly.

Piece of code named function.cpp:

#include <iostream>

std::pair <int[16][15],int> sites_diamond()
{
    int sites[16][15]={0};
    int N=0;
    for (int r=0; r<7; r++) {
        N=N+1+2*r;
        for (int c=0; c<(7-r);c++){
            sites[r][c]=0;
            sites[15-r][c]=0;
            sites[r][14-c]=0;
            sites[15-r][14-c]=0;
        }
    }
    N=2*(N+15);
    return std::make_pair(sites, N);
}

using namespace std;

int main(){
    std::pair <int[16][15], int> result = sites_diamond();
    cout << " sites \n"<<result.first<< endl;
    cout << "number \n"<<result.second<< endl;

    return 0;
}

Error I'm getting:

function.cpp: In function ‘std::pair<int [16][15], int> sites_diamond()’:
function.cpp:21:26: error: could not convert ‘std::make_pair<int (&)[16][15], int&>(sites, N)’ from ‘std::pair<int (*)[15], int>’ to ‘std::pair<int [16][15], int>’
     return std::make_pair(sites, N);

Thank you ahead for any suggestions. I work primarily in Python, but I want to rewrite a code to C++.

You can go with std::array . It is more C++-ish and you don't need to care about memory allocation/deallocation.

std::pair <std::array<std::array<int, 15>, 16>, int> sites_diamond()
{
    std::array<std::array<int, 15>, 16> sites;
    // ...
    return std::make_pair(sites, N);
}

and then the usage would be:

auto result = sites_diamond();
cout << " sites \n"  << result.first.size() << endl;
cout << " number \n" << result.second       << endl;

As the error is quite explanatory, I will just suggest the solution. Use pointers. Define your pair like this:

std::pair<int**, int> result;

Of-course, inside your function, change how you define sites:

int **sites;
sites = new int*[16];
for (int i = 0;i < 16;i++)
    sites[i] = new int[15];

Regarding

cout << " sites \n"<<result.first<< endl;

I don't know what are you trying to print here, it's gonna print some random address anyway.

Don't forget to delete this dynamically allocated memory when you are done. But all in all, I would just suggest to use something like vectors (2-d vector in this case, leak-proof too) in place of C-styled arrays.

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