This question already has an answer here:
这个问题已经有了答案:
- Returning multiple values from a C++ function 18 answers
- 从c++函数18返回多个值
Can I return two values from function one intiger and boolean? I tried to do this in this way but its doesnt work.
我能从函数1返回两个值吗?我试着这样做,但没有用。
int fun(int &x, int &c, bool &m){
if(x*c >20){
return x*c;
m= true;
}else{
return x+c;
m= false;
}
fun(x, c, m);
if(m) cout<<"returned true";
else cout<<"returned false";
}
2 个解决方案
#1
3
You can create a struct which contains two values as its members. You can then return that struct, and access the individual members.
您可以创建一个包含两个值作为成员的结构体。然后,您可以返回该结构体,并访问各个成员。
Thankfully, C++
does this for you by the pair
class. To return an int
and a bool
, you can use pair<int,bool>
.
谢天谢地,c++通过pair类为您实现了这一点。要返回int和bool,可以使用pair
#2
2
You can return a struct
that contains some values.
您可以返回包含一些值的结构。
struct data {
int a; bool b;
};
struct data func(int val) {
struct data ret;
ret.a=val;
if (val > 0) ret.b=true;
else ret.b=false;
return ret;
}
int main() {
struct data result = func(3);
// use this data here
return 0;
}
#1
3
You can create a struct which contains two values as its members. You can then return that struct, and access the individual members.
您可以创建一个包含两个值作为成员的结构体。然后,您可以返回该结构体,并访问各个成员。
Thankfully, C++
does this for you by the pair
class. To return an int
and a bool
, you can use pair<int,bool>
.
谢天谢地,c++通过pair类为您实现了这一点。要返回int和bool,可以使用pair
#2
2
You can return a struct
that contains some values.
您可以返回包含一些值的结构。
struct data {
int a; bool b;
};
struct data func(int val) {
struct data ret;
ret.a=val;
if (val > 0) ret.b=true;
else ret.b=false;
return ret;
}
int main() {
struct data result = func(3);
// use this data here
return 0;
}