从c++中的一个函数返回两个值
returning two values from one function in c++
我可以从函数返回两个值吗?我试着用这种方法做这件事,但没有用。
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";
}
您可以创建一个包含两个值作为其成员的结构。然后,您可以返回该结构,并访问各个成员。
值得庆幸的是,C++
通过pair
类为您完成了这项工作。要返回int
和bool
,可以使用pair<int,bool>
。
您可以返回包含一些值的struct
。
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;
}
相关文章:
- 如何返回一个类的两个对象相加的结果
- 返回两个向量 – 使用引用还是元组?
- 函数返回两个字符串的第一个常用字符
- C++函数返回两个 char 数组的相同索引元素
- 为什么同一个逻辑方程在python和c++中返回两个不同的结果
- 给定一个偶数(大于2),返回两个素数,其总和等于给定数
- 在C 中返回两个值对
- 在 C++ 中创建动态数组并返回两个值
- 在C++中返回两个字符串
- C++ 在数组中返回两个值
- 用移动语义返回两个对象
- Bit hack根据第二个值返回两个值中的一个
- 如何在C++中从函数返回两个值
- 返回两个用户输入值的函数
- 从c++中的一个函数返回两个值
- 我的C++DLL返回两个顺序调用混合的数据
- 如何使用boost元组返回两个向量
- 如何从lua函数返回两个或多个表
- 在c++函数中返回两个变量
- C++类用于使用复数相乘并返回两个值