Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在c+;中的函数中返回多个数组和变量+;(如MATLAB) 如何将几个变量和数组从函数返回到C++中的main函数中?(如MATLAB)_C++_Arrays_Function - Fatal编程技术网

在c+;中的函数中返回多个数组和变量+;(如MATLAB) 如何将几个变量和数组从函数返回到C++中的main函数中?(如MATLAB)

在c+;中的函数中返回多个数组和变量+;(如MATLAB) 如何将几个变量和数组从函数返回到C++中的main函数中?(如MATLAB),c++,arrays,function,C++,Arrays,Function,如果要从函数返回数组,建议使用std::array或std::vector。例如: std::vector<std::vector<float>> read_mesh(const char *filename) { std::vector<std::vector<float>> myvec(HEIGHT, std::vector<float>(WIDTH)); myvec[y][x] = ...; return

如果要从函数返回数组,建议使用
std::array
std::vector
。例如:

std::vector<std::vector<float>> read_mesh(const char *filename)
{
    std::vector<std::vector<float>> myvec(HEIGHT, std::vector<float>(WIDTH));
    myvec[y][x] = ...;
    return myvec;
}

int main()
{
    std::vector<std::vector<float>> myvec = read_mesh("");
}
std::矢量读取网格(常量字符*文件名)
{
std::vector myvec(高度,std::vector(宽度));
myvec[y][x]=。。。;
返回myvec;
}
int main()
{
std::vector myvec=读取网格(“”);
}

请注意,在本例中,
[y]
位于
[x]
之前。如果需要,可以交换维度。

可以使用std::tuple模板从函数返回多个值,并使用std::tie将tuple元素绑定到调用站点的各个变量:

#include <iostream>
#include <tuple>

std::tuple<int, int> foo() 
{
  return std::make_tuple(1, 2);
}

int main()
{
  int one, two;
  std::tie(one, two) = foo();
  std::cout << "one: " << one << ", two: " << two << std::endl;
}
#包括
#包括
std::tuple foo()
{
返回std::make_tuple(1,2);
}
int main()
{
int一,二;
std::tie(一,二)=foo();

std::cout
void main()
无效C++构建一个
struct
,将要返回的内容作为数据成员,并返回该
struct
的一个实例。要从一个函数返回多个变量,可以返回一个结构,也可以使用引用参数。但您的示例涉及返回“一个”这是一个数组,我就是这么回答的。
#include <iostream>
#include <tuple>

std::tuple<int, int> foo() 
{
  return std::make_tuple(1, 2);
}

int main()
{
  int one, two;
  std::tie(one, two) = foo();
  std::cout << "one: " << one << ", two: " << two << std::endl;
}