C++返回多个值
Return Multiple Values C++
有没有办法从一个函数返回多个值?在我正在处理的程序中,我希望将 4 个不同的 int 变量返回给主函数,从一个单独的函数,继续通过程序所需的所有统计信息。我找不到真正做到这一点的方法。任何帮助将不胜感激,谢谢。
对于 C++11 及更高版本,您可以使用 std::tuple
和 std::tie
进行非常符合 Python 返回多个值等语言风格的编程。例如:
#include <iostream>
#include <tuple>
std::tuple<int, int, int, int> bar() {
return std::make_tuple(1,2,3,4);
}
int main() {
int a, b, c, d;
std::tie(a, b, c, d) = bar();
std::cout << "[" << a << ", " << b << ", " << c << ", " << d << "]" << std::endl;
return 0;
}
如果您有 C++14,这会变得更干净,因为您不需要声明 bar
的返回类型:
auto bar() {
return std::make_tuple(1,2,3,4);
}
C++不支持
返回多个值,但您可以返回包含其他类型的实例的类型的单个值。例如
struct foo
{
int a, b, c, d;
};
foo bar() {
return foo{1, 2, 3, 4};
}
或
std::tuple<int, int, int, int> bar() {
return std::make_tuple(1,2,3,4);
}
或者,在 C++17 中,您将能够使用结构化绑定,它允许您从返回表示多个值的类型的函数初始化多个对象:
// C++17 proposal: structured bindings
auto [a, b, c, d] = bar(); // a, b, c, d are int in this example
一种解决方案是从函数返回一个向量:
std::vector<int> myFunction()
{
std::vector<int> myVector;
...
return myVector;
}
另一种解决方案是添加参数:
int myFunction(int *p_returnValue1, int *p_returnValue2, int *p_returnValue3)
{
*p_var1 = ...;
*p_var2 = ...;
*p_var3 = ...;
return ...;
}
在第二个示例中,您需要声明将包含代码的四个结果的四个变量。
int value1, value2, value3, value4;
之后,调用函数,将每个变量的地址作为参数传递。
value4 = myFunction(&value1, &value2, &value3);
编辑:这个问题之前已经问过,将其标记为重复。从C++函数返回多个值
编辑#2:我看到多个答案建议结构,但我不明白为什么"为单个函数声明结构"是相关的,因为显然有其他模式,例如用于此类问题的参数。
如果您希望 top 返回的所有变量的类型都相同,您可以只返回它们的数组:
std::array<int, 4> fun() {
std::array<int,4> ret;
ret[0] = valueForFirstInt;
// Same for the other three
return ret;
}
您可以使用一个需要 4 int
s 作为引用的函数。
void foo(int& a, int& b, int& c, int& d)
{
// Do something with the ints
return;
}
然后像使用它一样
int a, b, c, d;
foo(a, b, c, d);
// Do something now that a, b, c, d have the values you want
但是,对于这种特殊情况(4 个整数),我建议@juanchopanza的答案(std::tuple)。为了完整起见,我添加了此方法。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- 为什么模板类中的对象不能返回值