如何在C++中从函数返回两个值
How to return two values from a function in C++?
如何从函数返回整数和向量。在 c++11 中,我可以使用元组。但我必须使用C++98标准。
问题是这样的,
int myfunction(parameter 1,parameter 2)
{
vector<int> created_here;
//do something with created here
return int & created_here both
}
我该怎么做。顺便说一下,我必须递归使用我的函数。所以我曾这样想过,
int n;
vector<int> A;
int myfunction(int pos,int mask_cities,vector<int> &A)
{
if(mask = (1<<n)-1)
return 0;
vector<int> created_here;
int ans = 999999;
for(int i=0;i<n;++i){
int tmp = myfunction(pos+1,mask|1<<i,created_here);
if(tmp<ans){
A = created_here;
ans = tmp;
}
}
return ans;
}
这行得通吗?或者有更好的解决方案。顺便说一下,我的实际问题是找到旅行推销员问题的解决方案,这应该澄清我的需求<</p>
使用std::pair<>
:
std::pair<int, std::vector<int> > myfunction() {
int i;
std::vector<int> v;
return std::make_pair(i, v);
}
最好的方法是使用数据结构。
struct MyParam
{
int myInt;
vector<int> myVect;
} ;
MyParam myfunction( MyParam myParam )
{
return myParam;
}
在函数中创建向量并在进行递归函数调用时使用它将不是一个好的选择。
我建议您通过引用从主函数传递这两个参数(而不是全局声明它(如 OP 所做的那样),并在您递归调用函数时操作它们,而不是在每次调用中返回它们。
相关文章:
- 如何返回一个类的两个对象相加的结果
- 从两个窗口返回前景窗口
- 如何创建两个具有相同名称和不同返回类型并基于布尔参数运行的函数
- 返回两个向量 – 使用引用还是元组?
- 函数返回两个字符串的第一个常用字符
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 在函数中连接两个字符,并在 C++ 中返回输出
- C++函数返回两个 char 数组的相同索引元素
- 两个相同的重载运算符[]一个返回引用
- 为什么同一个逻辑方程在python和c++中返回两个不同的结果
- 在C++中将返回unique_ptr和shared_ptr的两个工厂方法组合为一个
- 从两个 lambda 的函数返回 lambda 时的链接器错误
- 如何通过返回类型区分两个 lambda 函数?
- C++ 超载 += 用于两个袋子的合并,返回类型为空隙
- 如何拥有两个名称相同但返回类型不同的纯虚拟方法
- 如何将两个 jlong 数据类型转换为 jstring,然后将两个字符串连接在一起以便从 JNI 将字符串返回给 jav
- 给定一个偶数(大于2),返回两个素数,其总和等于给定数
- 在C 中返回两个值对
- 两个返回相同值的 Arduino 类实例
- 为什么我在这里得到两个返回值