【问题标题】:How to pair 2D array and integer in the output of the function?如何在函数的输出中配对二维数组和整数?
【发布时间】:2021-04-05 05:23:13
【问题描述】:

我正在努力从一个函数创建多变量输出:我想返回二维数组 sites(16x15) 和整数 N

我试过了:

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

我的问题是我可能不知道如何在函数的声明中定义一个二维数组std::pair ,int> 正确。

一段名为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;
}

我得到的错误:

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

感谢您的任何建议。 我主要使用 Python 工作,但我想将代码重写为 C++。

【问题讨论】:

  • 而不是原始数组定义,而是使用std::array&lt;std::array&lt;int,15&gt;,16&gt;。这将使将数组作为值处理更容易。
  • 我假设发布的代码不是真实的(它多次为数组分配零值),但声明 N 的值仅取决于 15 和 16 是否正确?
  • 请查看答案并标记解决您问题的答案

标签: c++ function c++11


【解决方案1】:

您可以使用std::array。它更像是 C++,你不需要关心内存分配/释放。

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

然后用法是:

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

【讨论】:

    【解决方案2】:

    由于错误很容易解释,我只建议解决方案。使用指针。 像这样定义你的配对:

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

    当然,在你的函数中,改变你定义网站的方式:

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

    关于

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

    我不知道你想在这里打印什么,反正它会打印一些随机地址。

    完成后不要忘记delete 这个动态分配的内存。 但总而言之,我只是建议使用向量之类的东西(在这种情况下是二维向量,也是防泄漏的)来代替 C 样式的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 2018-02-28
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 2023-02-13
      • 2011-04-10
      相关资源
      最近更新 更多