C++ 返回多个值C++;
有没有一种方法可以从一个函数返回多个值?在我正在开发的一个程序中,我希望将4个不同的int变量从一个单独的函数返回到主函数,所有的stats都需要在程序中继续。我没有办法真正做到这一点。非常感谢您的帮助。C++不支持返回多个值,但您可以返回包含其他类型实例的类型的单个值。比如说,C++ 返回多个值C++;,c++,function,variables,return,C++,Function,Variables,Return,有没有一种方法可以从一个函数返回多个值?在我正在开发的一个程序中,我希望将4个不同的int变量从一个单独的函数返回到主函数,所有的stats都需要在程序中继续。我没有办法真正做到这一点。非常感谢您的帮助。C++不支持返回多个值,但您可以返回包含其他类型实例的类型的单个值。比如说, struct foo { int a, b, c, d; }; foo bar() { return foo{1, 2, 3, 4}; } 或 如果希望top返回的所有变量的类型相同,则只需返回它们的数组即
struct foo
{
int a, b, c, d;
};
foo bar() {
return foo{1, 2, 3, 4};
}
或
如果希望top返回的所有变量的类型相同,则只需返回它们的数组即可:
std::array<int, 4> fun() {
std::array<int,4> ret;
ret[0] = valueForFirstInt;
// Same for the other three
return ret;
}
std::array fun(){
std::数组ret;
ret[0]=valueForFirstInt;
//其他三个也一样
返回ret;
}
一种解决方案是从函数返回向量:
std::vector<int> myFunction()
{
std::vector<int> myVector;
...
return myVector;
}
在第二个示例中,您需要声明将包含代码的四个结果的四个变量
int value1, value2, value3, value4;
然后,调用函数,将每个变量的地址作为参数传递
value4 = myFunction(&value1, &value2, &value3);
编辑:以前曾提出过此问题,将其标记为重复。
编辑#2:我看到多个答案建议使用一个结构,但我不明白为什么“为单个函数声明一个结构”是相关的,因为它们显然是其他模式,如用于此类问题的out参数。您可以使用一个以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)。为了完整性,我添加了这种方法。对于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;
}
好的,那么我如何将这4个返回值作为变量保存回main呢?他们会自动覆盖以前的内容,还是我必须手动让他们这样做?对不起,我还是C++的新手。我很确定这就是我来这里的原因,但是无论如何,请看我的答案:如何使用<代码> STD::TIA/<代码>在返回端。有问题吗?如果您能发表评论,我将不胜感激,这样我就可以编辑/删除答案了。不!非常好,谢谢
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
#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;
}
auto bar() {
return std::make_tuple(1,2,3,4);
}