从c++中的一个函数返回两个值

returning two values from one function in c++

本文关键字:返回 两个 函数 一个 c++      更新时间:2023-10-16

我可以从函数返回两个值吗?我试着用这种方法做这件事,但没有用。

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类为您完成了这项工作。要返回intbool,可以使用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;
}