js c++ 多值返回 返回多个值 c++ tuple

返回多个值

使用C# 7.0推出的值元组和解构功能。
static (int, int) Calc(int a, int b)
{
    return (a + b, a - b);
}
static void Main()
{
    var (add, sub) = Calc(8, 2);
    Console.WriteLine($"{add}, {sub}");
}

Scala

使用元组。
def calc(a: Int, b: Int) : (Int, Int) = {
    (a + b, a - b)
}
val (add, sub) = calc(8, 2)
println(s"$add, $sub")

Kotlin

使用Pair和解构声明。
fun calc(a: Int, b: Int): Pair<Int,Int> {
    return Pair(a + b, a - b)
}
fun main() {
    val (add, sub) = calc(8, 2)
    println("$add, $sub")
}
使用数组和解构声明。
fun calc(a: Int, b: Int) : Array<Int> {
    return arrayOf(a + b, a - b)
}
fun main() {
    val (add, sub) = calc(8, 2)
    println("$add, $sub")
}

JavaScript

使用解构赋值。
function calc(a, b) {
    return [a + b, a - b];
}
let [add, sub] = calc(8, 2);
console.log(`${add}, ${sub}`);

Python

使用元组和解构。
def calc(a, b):
    return a + b, a - b


add, sub = calc(8, 2)
print(f"{add}, {sub}")
使用列表和解构。
def calc(a, b):
    return [a + b, a - b]


add, sub = calc(8, 2)
print(f"{add}, {sub}")

Go

使用元组。
func calc(a int, b int) (int, int) {
    return a + b, a - b
}
func main() {
    add, sub := calc(8, 2)
    fmt.Println(add, sub)
}

C++

使用元组和结构化绑定声明。
tuple<int, int> calc(int a, int b)
{
    return make_tuple(a + b, a - b);
}
int main()
{
    auto [add, sub] = calc(8, 2);
    cout << add << ", " << sub << endl;
    return 0;
}

注意:
make_tuple不能写成 make_tuple<int, int>(...), 要缺省掉模板参数,让编译器自动推导。msvc编译器会报错,编译不过。
#include <iostream>
#include <tuple>
#include <functional>
 
std::tuple<int, int> f() // this function returns multiple values
{
    int x = 5;
    return std::make_tuple(x, 7); // return {x,7}; in C++17
}
 
int main()
{
    // heterogeneous tuple construction
    int n = 1;
    auto t = std::make_tuple(10, "Test", 3.14, std::ref(n), n);
    n = 7;
    std::cout << "The value of t is "  << "("
              << std::get<0>(t) << ", " << std::get<1>(t) << ", "
              << std::get<2>(t) << ", " << std::get<3>(t) << ", "
              << std::get<4>(t) << ")\n";
 
    // function returning multiple values
    int a, b;
    std::tie(a, b) = f();
    std::cout << a << " " << b << "\n";
}

 

 

Ruby

使用解构赋值。
def calc(a, b)
    return [a + b, a - b]
end
a, b = calc(8, 2)
puts "#{a}, #{b}"

Swift

func calc(a: Int, b: Int) -> (Int, Int) {
    return (a + b, a - b)
}
let (add, sub) = calc(a:8, b:2)
print("\(add), \(sub)")

F#

let calc a b = 
    a + b, a - b

[<EntryPoint>]
let main argv =
    let add, sub = calc 8 2
    printfn "%d, %d" add sub
    0

Groovy

def calc(a, b) {
    return [a + b, a - b]
}
def (add, sub) = calc(8, 2)
println("${add}, ${sub}")

Perl 6

sub calc($a, $b) {
    return ($a + $b, $a - $b);
}
my ($add, $sub) = calc(8, 2);
print "$add, $sub";

 

 
posted @ 2021-12-30 15:05  Bigben  阅读(150)  评论(0编辑  收藏  举报