[序]:
首先,非常感谢最近结识到的一个好朋友,是他给了我这样的一个idea,让我决定写下这篇博文。
如果这篇博文恰好能帮助阅读到这篇博文的你,我觉得,还是有必要同时去感谢下他。
[正文]:
C++的返回的话,对于很多刚接触C++不久的人来说,一般会是直接返会返会标准库自带的类型,如(float,double,int,char或者是string)。随着实力的提高和遇到的题目的难度的提高,会有部分题目,或者是部分内容要求到去返回多个变量,或者是组合变量。部分人,可能会由于是超前学习,或者什么的,遇到困惑。而我会在这篇文章中,尽自己所能去讲解清楚。
[前提]:
为了描述,我会围绕着一个题目,来进行讲解;
[题目]:
在一个二维数组中,返回我们想要的值的位置。(x,y)
第一个版本:
描述:运用了pair(STL内容,不用担心,这个只是一个很帮助的工具,操作起来也是非常容易的)不需要调用其他什么库。#include<iostream> using namespace 就好了。
typedef pair<int,int> pInt;
pInt f3(vector< vector<int> > VII,int n) {
for (int i = 0; i < VII.size(); ++i) {
for (int j = 0; j < VII[i].size(); ++j) {
if (VII[i][j] == n)
{
return {i,j};
}
}
}
}
为了描述的方便,我在这使用了typedef,只是为了表述清楚。如果您先学过Python,想必也会知道,import ...as..这样的操作了。大致是一个意思。
不用担心,我写了一个没有typedef的。
pair<int,int> f3(vector< vector<int> > VII,int n) {
for (int i = 0; i < VII.size(); ++i) {
for (int j = 0; j < VII[i].size(); ++j) {
if (VII[i][j] == n) {
return {i,j};
}
}
}
}
至于怎么使用这个返回值,我写了一个在main函数中的片段,供大家使用。
pInt ans2 = f3(VII,12);
cout << ans2.first<< " "<< ans2.second<< endl;
而这时的VII,即是二维的vector;
第二个版本:采用vector<int>实现
vector<int> f2(vector< vector<int> > VII,int n) {
for (int i = 0; i < VII.size(); ++i) {
for (int j = 0; j < VII[i].size(); ++j) {
if (VII[i][j] == n)
{
vector <int> v;
v.push_back(i);
v.push_back(j);
return v;
}
}
}
}
同样,在main函数中,用一个vector<int>来记录的。
vector<int> ans = f2(VII,12);
if (ans.size() == 2) {
cout << ans[0]<< " "<< ans[1]<< endl;
}
第三个版本:用vector来返回,但是,用的是int a[100][100]
vector<int> f1(int a[100][100],int n) {
//find a[i][j] == n return {i,j};
for (int i = 0; i < 100; ++i) {
for (int j = 0; j < 100; ++j) {
if (a[i][j] == n) {
vector<int> v;
v.push_back(i);
v.push_back(j);
return v;
}
}
}
}
这其实与之前的第二个版本没有太多的区别。
第四个版本:
描述:用struct的结构体来做,优点是,你可以返回的不是像pair一样有数量限制,像vector一样必须要求是一样的类型。缺点就是,你得理解类(class)。当然,你要是一个JAVA工程师(膜,您可以不用看的),或者是未来的JAVA工程师,那这个还是推荐你看一看。
struct Node{
int x,y;
Node(int xx = -1,int yy = -1):x(xx),y(yy){};
};
Node f3(vector< vector<int> > VII,int n) {
for (int i = 0; i < VII.size(); ++i) {
for (int j = 0; j < VII[i].size(); ++j) {
if (VII[i][j] == n)
{
return Node(i,j);
}
}
}
}