在c++ [duplicate]中从一个函数返回两个值

时间:2022-01-27 01:03:59

This question already has an answer here:

这个问题已经有了答案:

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 ,bool>

#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 ,bool>

#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;
}