男男床做视频网站,jimdo和wordpress,沐风wordpress,网站会员管理系统C不像python可以轻易地处理多值返回问题#xff0c;处理使用指针或者引用将需要返回的值通过参数带出来#xff0c;还有几种特殊的方式。 引用自#xff1a;https://mp.weixin.qq.com/s/VEvUxpcJPsxT9kL7-zLTxg
1. Tuple tie
通过使用std::tie#xff0c;我们可以将tuple…C不像python可以轻易地处理多值返回问题处理使用指针或者引用将需要返回的值通过参数带出来还有几种特殊的方式。 引用自https://mp.weixin.qq.com/s/VEvUxpcJPsxT9kL7-zLTxg
1. Tuple tie
通过使用std::tie我们可以将tuple中的元素解包到不同的变量中。 std::tie 通常用于创建元组或者用于解构元组。主要用途有两个将多个变量绑定到一个元组或者从元组中解构多个值。
将多个变量绑定到一个元组
#include tuple
#include iostreamint 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::get0(myTuple) , std::get1(myTuple) , std::get2(myTuple) std::endl;return 0;
}从元组中解构多个值
#include tuple
#include iostreamint main() {std::tupleint, 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::tupleint, 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 结构体绑定
C17引入了结构体绑定可以方便地从结构体、数组、元组等数据结构中将其中的成员变量绑定到命名的变量上常与auto一起使用
结构体绑定的含义
#include iostream
#include tuplestruct Point {int x;int y;
};int main() {// demo1Point p {10, 20};// 使用结构化绑定从结构体中解构成员你可以直接使用 x 和 y 访问结构体的成员而不需要使用 p.x 和 p.y。 auto [x, y] p;// demo2std::tupleint, 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::functionvoid(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;
};//这是 C17 中的类模板参数推导的语法。这行代码告诉编译器如何根据构造函数的参数类型推导出模板参数。它的意思是当你提供 T1 和 T2 类型的构造函数参数时编译器应该推导出 manyT1, T2 类型。
template class T1, class T2
many(T1, T2) - manyT1, T2;//这里使用了结构化绑定structured binding和自动类型推导auto将 divide 函数返回的 many 结构体对象的 quotient 和 remainder 成员分别赋值给变量 quotient 和 remainder。在这里编译器会根据 many 模板的构造函数推导出正确的类型即 manyint, 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) - manyT1, T2;manyint, int divide(int dividend, int divisor) {return many{dividend / divisor,dividend % divisor,};
}auto [quotient, remainder] divide(14, 3);