C++元组与对组

来自于👉 tuple - C++ Reference (cplusplus.com) 并整理

一个元组std::tuple是一个能够容纳 元素集合 的对象。每个元素都可以是 不同的类型

std::make_pair()可以构建一个配对对象,其第一个元素设置为x,第二个元素设置为y,并返回。

std::tie可以绑定std::tuple<T,T,T,...>的实例,并分别给这些元素起别名


std::tuple

所在头文件 <tuple>

例子:

// tuple example
#include <iostream>     // std::cout
#include <tuple>        // std::tuple, std::get, std::tie, std::ignore

int main () {
    std::tuple<int,char> foo (10,'x');
    auto bar = std::make_tuple ("test", 3.1, 14, 'y');
    std::cout << "bar has "<<std::tuple_size<decltype(bar)>::value << elements<< '\n';
	std::tuple_element<0,decltype(bar)>::type first = std::get<0>(bar);
    std::cout << "bar contains: " << first << '\n';
    
    std::get<2>(bar) = 100;                                    // access element

    int myint; char mychar;

    std::tie (myint, mychar) = foo;                            // unpack elements
    std::tie (std::ignore, std::ignore, myint, mychar) = bar;  // unpack (with ignore)

    mychar = std::get<3>(bar);

    std::get<0>(foo) = std::get<2>(bar);
    std::get<1>(foo) = mychar;

    std::cout << "foo contains: ";
    std::cout << std::get<0>(foo) << ' ';
    std::cout << std::get<1>(foo) << '\n';

    return 0;
}

答案:

bar has 4 elements
bar contains: test
foo contains: 100 y

std::tie

所在头文件 <tuple>

例子:

// packing/unpacking tuples
#include <iostream>     // std::cout
#include <tuple>        // std::tuple, std::make_tuple, std::tie

int main () {
    std::tuple<int,float,char> mytuple;

    mytuple = std::make_tuple (10, 2.6, 'a');          // packing values into tuple

    int myint;
    char mychar;
    std::tie (myint, std::ignore, mychar) = mytuple;   // unpacking tuple into variables

    std::cout << "myint contains: " << myint << '\n';
    std::cout << "mychar contains: " << mychar << '\n';

    return 0;
}

结果:

myint contains: 10
mychar contains: a

std::pair

所在头文件 <utility>

例子:

// make_pair example
#include <utility>      // std::pair
#include <iostream>     // std::cout

int main () {
    std::pair <int,int> foo;
    std::pair <int,int> bar;

    foo = std::make_pair (10,20);
    bar = std::make_pair (10.5,'A'); // ok: implicit conversion from pair<double,char>

    std::cout << "foo: " << foo.first << ", " << foo.second << '\n';
    std::cout << "bar: " << bar.first << ", " << bar.second << '\n';
	std::cout<< "foo contains: " << std::get<0>(foo) << " and " << std::get<1>(foo) << '\n';
    
    return 0;
}

结果:

foo: 10, 20
bar: 10, 65
foo contains: 50 and x

End.