可能重复:
一个函数能返回多个值吗?
我想从一个C++函数返回3个变量,但是一个函数只能有一个返回值,我该如何返回3个值。尝试使用return(5,4);但这是一个语法错误。
可能重复:
一个函数能返回多个值吗?
我想从一个C++函数返回3个变量,但是一个函数只能有一个返回值,我该如何返回3个值。尝试使用return(5,4);但这是一个语法错误。
C++函数只能返回一个值。然而,你可以将多个值封装在一个类或结构体中返回。
struct Foo
{
int value1;
int value2;
};
Foo SomeFunction()
{
Foo result = { 5, 4 };
return result;
}
如果你的编译器支持,你可以使用 std::tuple
。
#include <tuple>
std::tuple<int, int, int> SomeFunction()
{
return std::make_tuple(5, 4, 3);
}
如果您事先不知道要返回多少个值,那么使用 std::vector
或类似的容器是最好的选择。
您还可以通过将函数的指针或引用参数传递给函数并在函数中修改它们来返回多个值,但我认为返回复合类型通常是更“清晰”的方法。
std::tie
。https://dev59.com/L3E85IYBdhLWcg3w3Xlp#2573822 - fdermishinmain()
函数中写入元组后,您将如何打印它?auto tup= swap(a,b); std::cout << tup << std::endl;
。我收到了 error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
错误提示,请您有什么建议吗? - Anustruct values
{
int i;
int j;
char *other;
};
values f()
{
values v = {/*....*/};
//...
return v;
}
如果所有值的类型相同,那么您可以使用以下方式来使用std::vector
:
#include <vector> //must include it!
std::vector<int> f()
{
std::vector<int> v;
v.push_back(5);
v.push_back(4);
//so on
//...
return v;
}
还有其他的容器,例如std::map
、std::list
、std::stack
等等。使用最适合您的容器即可。同样还有std::pair
,它只包含两个值,正如其名称所示。
在C++中,你只能返回一个值。如果需要返回更多信息,请返回一个结构体(或像std::vector
这样的容器),或将一些变量作为非const引用(或指针)传入并更改它们。
If you have objects of the same type, std::array
would be a good return type for that.
If you have varying numbers, use std::vector
instead.
If you have (a fixed number of) different types, use std::tuple
:
std::tuple <int, long, double> f()
{
return std::tuple <int, long, double>( 42, 4711l, 3.141 );
}
4711
而不是4711l
呢? - sbi您可以使用 std::pair
表示两个结果,如果需要表示两个以上的结果,则可以考虑使用 boost::tuple
。它甚至可以在同一个元组中处理不同类型的数据。
pair<pair<A, B>, C>
来模拟一个 triple<A, B, C>
:-) - fredoverflow这里大部分的答案都是正确的,你应该返回一个结构体。
如果你有兴趣,还有一种方法,那就是通过发送你想要返回的变量的引用来实现。
例如:
#include<iostream>
#include<cstdio>
using namespace std;
bool f(int a,int b,int& q,int& r)
{
if(b==0)return 0;
q=a/b;
r=a%b;
return 1;
}
int main()
{
int a=64,b=7,q,r;
bool pos=f(a,b,q,r);
if(pos)
{
printf("Quotient = %d Remainder = %d\n",q,r);
}
else
{
printf("Divison by zero not possible!\n");
}
return 0;
}
不是,但有两种方法可以实现:
1)将指向“返回”值的指针作为参数传递,您可以在函数中更改其值。
2)您可以创建一个包含所有这些值并返回该结构的struct
。只有在确实需要时才使用此选项,第一种解决方案要好得多。
struct a
{
int x;
int y;
int z;
};
b()
{
a.x = 2;
a.y = 4;
a.z = 8;
return a;
}
return (a, b, c, ... , n)
语句中,a
、b
、c
等变量由逗号操作符分隔,表达式的值为最右边的操作数n
。因此,语法是正确的,但不会返回多个值。
要返回多个值:
在函数中返回多个值是可能的,你必须使用指针。此外,也可以通过使用指针参数来实现,指针参数会保留它们的值。
有关使用指针返回多个值的详细用法,请参阅http://www.techyv.com/questions/how-do-i-return-multiple-variables-c-function。