在C++函数中返回两个变量

32

我希望在调用我创建的函数时返回两个双精度变量。

根据一些基础C++教程,似乎无法实现此功能。

是否有方法可以实现这一点?


1
请查看 https://dev59.com/RnRC5IYBdhLWcg3wXPwC。 - Fred Larson
以防万一有人(比如我!)忘记了如何在C中实现,诀窍是将指针传递给函数并“返回”void。例如,一个接收两个double(x,y)并返回向量除以范数(x / d,y / d)的函数,其中d = sqrt(x² + y²):`void normalized(double x1,double x2,double * vector){ double norm; norm = sqrt(x1 * x1 + x2 * x2); vector [1] = x1 / norm; vector [2] = x2 / norm; }` - MCL
8个回答

53

您可以编写一个简单的结构体来保存变量并返回它,或者使用std::pairstd::tuple

#include <utility>

std::pair<double, double> foo()
{
  return std::make_pair(42., 3.14);
}

#include <iostream>
#include <tuple> // C++11, for std::tie
int main()
{
  std::pair<double, double> p = foo();
  std::cout << p.first << ", " << p.second << std::endl;

  // C++11: use std::tie to unpack into pre-existing variables
  double x, y;
  std::tie(x,y) = foo();
  std::cout << x << ", " << y << std::endl;

  // C++17: structured bindings
  auto [xx, yy] = foo(); // xx, yy are double
}

3
还可以提到 std::tie,它可用于将返回值捕获到两个已存在的单独变量中。 - Benjamin Lindley
@BenjaminLindley 好建议。已添加一个例子。 - juanchopanza
4
现在你可以使用 return { 42., 3.14 };,这样更加简洁高效(如果你在另一端使用了 tie(x,y),则避免了构造一个pair)。 - WurmD

20
如果您使用的是C++11,我建议使用std::tuplestd::tie来实现。以下示例取自我提供链接的std::tuple页面:
#include <tuple>
#include <iostream>
#include <string>
#include <stdexcept>

std::tuple<double, char, std::string> get_student(int id)
{
    if (id == 0) return std::make_tuple(3.8, 'A', "Lisa Simpson");
    if (id == 1) return std::make_tuple(2.9, 'C', "Milhouse Van Houten");
    if (id == 2) return std::make_tuple(1.7, 'D', "Ralph Wiggum");
    throw std::invalid_argument("id");
}

int main()
{
    auto student0 = get_student(0);
    std::cout << "ID: 0, "
              << "GPA: " << std::get<0>(student0) << ", "
              << "grade: " << std::get<1>(student0) << ", "
              << "name: " << std::get<2>(student0) << '\n';

    double gpa1;
    char grade1;
    std::string name1;
    std::tie(gpa1, grade1, name1) = get_student(1);
    std::cout << "ID: 1, "
              << "GPA: " << gpa1 << ", "
              << "grade: " << grade1 << ", "
              << "name: " << name1 << '\n';
}

19

你可以将两个双精度浮点数的引用传入一个函数,在函数内部设置它们的值。

void setTwoDoubles(double& d1, double& d2)
{
    d1 = 1.0;
    d2 = 2.0;
}

double d1, d2;
setTwoDoubles(d1, d2);
std::cout << "d1=" << d1 << ", d2=" << d2 << std::endl

7

3
在C++11中,您可以使用 tie 直接将值赋给两个变量。 - Edward Strange

4

从技术上讲,你不能像返回一个变量那样返回两个变量。不过,你可以使用引用。这样,你就可以将多个变量传递给函数,并且函数会对它们进行赋值,而不是返回任何内容:

void function(double & param1, double & param2) {
    param1 = 6.28;
    param2 = 3.14;
}

您可以这样调用:

double var1, var2;
function(var1, var2);

2

直接返回值是不可能的(因为返回值是单数)。
但是,您可以将一些值放入结构中,并返回该结构(例如pair<>)。

常见的模式是通过引用返回输出变量:

ReturnVal Myfunction(/*in*/ BlahType _someParameters, /*out*/ ReturnType& _firstReturn, /*out*/ OtherReturnType& _secondReturn)
{
   _firstReturn = //someStuff
   _secondReturn = //someOtherStuff


return SUCCESS;
}

2

不,你不能返回两个变量,你需要使用按引用传递的方法,如下所示:

    #include <iostream>
using namespace std;

// function declaration
void swap(int &x, int &y);

int main ()
{
   // local variable declaration:
   int a = 100;
   int b = 200;

   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;

   /* calling a function to swap the values using variable reference.*/
   swap(a, b);

   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;

   return 0;
}


// function definition to swap the values.
void swap(int &x, int &y)
{
   int temp;
   temp = x; /* save the value at address x */
   x = y;    /* put y into x */
   y = temp; /* put x into y */

   return;
}

输出结果将为:

   100   // 调用swap函数前的x值
   200   // 调用swap函数前的y值
   200   // 调用swap函数后的x值
   100   // 调用swap函数后的y值

这表示返回了两个值。

这个链接可以帮助您。


嗨,我认为由于C++ 11(及以上版本)的新功能,如std::pair,需要修改此答案。 - WY Hsu

0

一个函数无法返回两个值,但你可以返回一个指向包含这两个 double 值的数组或其他结构体的指针。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接