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

Zeu*_*s M 18 c++

我想返回两个双变量:调用我创建的函数时.根据一些教程(处理C++的基础知识),我将无法做到这一点.

有办法吗?

jua*_*nza 32

您可以编写一个包含变量并返回变量的简单结构,或使用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
}
Run Code Online (Sandbox Code Playgroud)

  • 也可能想提一下[`std :: tie`](http://en.cppreference.com/w/cpp/utility/tuple/tie),它可以用来捕获两个独立的,预先存在的回报变量. (2认同)
  • 同样,现在您可以执行“ return {42.,3.14};”,它甚至更漂亮,更快(如果另一边有“ tie(x,y)”,则可以避免构造一对) (2认同)

sim*_*onc 17

您可以将对两个双精度的引用传递给函数,并在函数内设置它们的值

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
Run Code Online (Sandbox Code Playgroud)


Tim*_*lds 16

如果您使用的是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';
}
Run Code Online (Sandbox Code Playgroud)


unw*_*ind 5

std::pair例如,您可以使用a .

  • 然后在C++ 11中,您可以使用`tie`直接分配给两个变量. (3认同)