C++不像python可以轻易地处理多值返回问题,处理使用指针
或者引用
将需要返回的值通过参数带出来,还有几种特殊的方式。
引用自:https://mp.weixin.qq.com/s/VEvUxpcJPsxT9kL7-zLTxg
1. Tuple+ tie
通过使用std::tie
,我们可以将tuple
中的元素解包到不同的变量中。
std::tie
通常用于创建元组或者用于解构元组。主要用途有两个:将多个变量绑定到一个元组,或者从元组中解构多个值。
将多个变量绑定到一个元组
#include <tuple>
#include <iostream>int main() {int a = 1;double b = 2.5;char c = 'A';// 使用 std::tie 将多个变量绑定到一个元组auto myTuple = std::tie(a, b, c);// 修改变量的值,元组中的值也会相应修改a = 10;b = 20.5;c = 'Z';// 打印元组的值std::cout << "Tuple values: " << std::get<0>(myTuple) << ", " << std::get<1>(myTuple) << ", " << std::get<2>(myTuple) << std::endl;return 0;
}
从元组中解构多个值
#include <tuple>
#include <iostream>int main() {std::tuple<int, double, std::string> myTuple = std::make_tuple(42, 3.14, "Hello");int x;double y;std::string z;// 使用 std::tie 从元组中解构多个值std::tie(x, y, z) = myTuple;// 打印解构出的值std::cout << "x: " << x << ", y: " << y << ", z: " << z << std::endl;return 0;
}
std::tie
提供了一种简洁的方式来处理元组或多个变量的结合,使得代码更易读和维护。
处理多值返回
std::tuple<int, int> divide(int dividend, int divisor) {return std::make_tuple(dividend / divisor, dividend % divisor);
}std::tie(quotient, remainder) = divide(14, 3);
std::cout << quotient << ", " << remainder << std::endl;
Struct Binding 结构体绑定
C++17引入了结构体绑定,可以方便地从结构体、数组、元组等数据结构中将其中的成员变量绑定到命名的变量上,常与auto
一起使用
结构体绑定的含义
#include <iostream>
#include <tuple>struct Point {int x;int y;
};int main() {// demo1Point p = {10, 20};// 使用结构化绑定从结构体中解构成员,你可以直接使用 x 和 y 访问结构体的成员,而不需要使用 p.x 和 p.y。 auto [x, y] = p;// demo2std::tuple<int, double, std::string> myTuple = {42, 3.14, "Hello"};// 使用结构化绑定从元组中解构成员auto [x, y, z] = myTuple;
}
结构体绑定解决多值返回
auto divide(int dividend, int divisor) {struct result {int quotient;int remainder;};return result{dividend / divisor, dividend % divisor};
}
auto [quotient, remainder] = divide(14, 3);
函数callback
通过传递处理返回值的callback,让用户自定义处理,这样便实现了返回多个值,实现更加灵活的代码结构。
void divide(int dividend, int divisor, std::function<void(int, int)> callback) {callback(dividend / divisor, dividend % divisor);
}
模版推导
这个有点复杂,GPT解释如下:
//这里定义了一个模板结构体 many,它有两模板参数 T1 和 T2,并包含两个成员变量 quotient 和 remainder 分别是类型 T1 和 T2。
template <typename T1, typename T2>
struct many {T1 quotient;T2 remainder;
};
//这是 C++17 中的类模板参数推导的语法。这行代码告诉编译器如何根据构造函数的参数类型推导出模板参数。它的意思是,当你提供 T1 和 T2 类型的构造函数参数时,编译器应该推导出 many<T1, T2> 类型。
template <class T1, class T2>
many(T1, T2) -> many<T1, T2>;
//这里使用了结构化绑定(structured binding)和自动类型推导(auto),将 divide 函数返回的 many 结构体对象的 quotient 和 remainder 成员分别赋值给变量 quotient 和 remainder。在这里,编译器会根据 many 模板的构造函数推导出正确的类型,即 many<int, int>
auto [quotient, remainder] = divide(14, 3);
模版推导处理多值返回
template <typename T1, typename T2>
struct many {T1 quotient;T2 remainder;
};template <class T1, class T2>
many(T1, T2) -> many<T1, T2>;many<int, int> divide(int dividend, int divisor) {return many{dividend / divisor,dividend % divisor,};
}auto [quotient, remainder] = divide(14, 3);