Home >Backend Development >C++ >How to determine the shape when a C++ function returns a multidimensional array?

How to determine the shape when a C++ function returns a multidimensional array?

WBOY
WBOYOriginal
2024-04-20 18:39:01912browse

To determine the shape of a multidimensional array returned by a C function, use the following steps: Use size() to determine the number of rows in the array. Use shape()[0] or arr[0].size() to determine the number of columns in the array.

C++ 函数返回多维数组时如何确定形状?

Use the Size-Shape attribute to determine the shape of a multidimensional array returned by a C function

When returning a multidimensional array from a C function, it is required Determine the shape of the array so that array elements can be processed correctly. Here's how to determine the shape using the size() and shape() methods:

#include <iostream>
#include <vector>

using namespace std;

vector<vector<int>> create_2d_array(int rows, int cols) {
  vector<vector<int>> arr(rows, vector<int>(cols));
  return arr;
}

int main() {
  // 创建一个 3x4 的二维数组
  vector<vector<int>> arr = create_2d_array(3, 4);

  // 获取数组的形状
  int rows = arr.size();
  int cols = arr[0].size();

  // 访问数组元素
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      cout << arr[i][j] << " ";
    }
    cout << endl;
  }

  return 0;
}

Output:

0 0 0 0
0 0 0 0
0 0 0 0

In this example, the create_2d_array function Returns a 3x4 two-dimensional array. The size() and shape() methods are used to determine the shape of the array so that array elements can be accessed correctly.

The above is the detailed content of How to determine the shape when a C++ function returns a multidimensional array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn