在C ++函数中返回两个变量 [英] Returning two variables in a C++ function
本文介绍了在C ++函数中返回两个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想返回两个双变量:当调用我创建的函数。
根据一些教程(处理C ++的基础知识),我将无法做到这一点。
I would like to return two double variables: when calling a function that I have created. According to some tutorials (which deal with the basics of the C++), I would be unable to do that.
有办法吗?
推荐答案
您可以编写一个简单的结构来保存变量并返回,或者使用 std: :pair
或 std :: tuple
:
You could write a simple struct that holds the variables and return it, or use an std::pair
or std::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 proposal: structured bindings
auto [xx, yy] = foo(); // xx, yy are double
}
这篇关于在C ++函数中返回两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文