从主函数返回多维向量,如何正确使用? [英] Return multidimensional vector from function for use in main, how to use correctly?

查看:119
本文介绍了从主函数返回多维向量,如何正确使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现使用vector是实现我需要做的最好的方法,但是我现在需要一些说明。



我需要生成一个多维数组在一个外部CPP中的函数中,然后在main中使用这个数组。 $ p> //包含向量,使用名称空间等
function(2,4);

//如何访问vector元素 - vectorname [2] [4] - > classvar; ?

vectors.cpp

  void function(value1,value2){
// class def
int value1 = value1;
int value2 = value2;
vector< int>(value1)< vector< Class>(value2)vectorname> ;; //语法不正确?或新的*矢量?

返回vectorname; //?


解决方案

$ c> vector 需要一点习惯。 int 的2D矢量如下所示:

  vector< vector< INT> > myVector; 

如果您想设置特定维度,请使用大小为

的构造函数:

  vector< vector< int> > myVector(10,vector< int>(5)); 

这产生了一个 10x5 零向量。你可以做到这一点

  vector< vector< int> > myVector(10,vector< int>(5,-1)); 

为元素提供初始值( -1 )。

作为一个经验法则,您希望您的向量通过引用传递并由值返回。


I've found that using a vector is the best way to achieve what I need to do, however I now need some clarification.

I need to generate a multidimensional array within a function in an external CPP, then make this available within main.

main.cpp

// include vector, using namespace etc.
function(2, 4);

// how to access vector elements here - vectorname[2][4]->classvar;  ? 

vectors.cpp

void function(value1, value2){
// class def
int value1 = value1;
int value2 = value2;
 vector<int>(value1)<vector<Class>(value2) vectorname>; // incorrect syntax? or new * vector ?

return vectorname; // ?
}

解决方案

The syntax with vector requires a little getting used to. A 2D vector of int looks like this:

vector<vector<int> > myVector;

If you would like to set specific dimensions, use constructors that take size:

vector<vector<int> > myVector(10, vector<int>(5));

This produces a 10x5 vector of zeros. You can do this

vector<vector<int> > myVector(10, vector<int>(5, -1));

to provide initial values for your elements (-1 in this case).

As a rule of thumb, you want your vectors passed by reference and returned by value.

这篇关于从主函数返回多维向量,如何正确使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆