2017年1月3日 星期二

[C++] tuple Usage

在 c++11,tuple 變成一個內建的 data structure

這邊記錄一下一些 sample code

<Example 1> Basic usage

#include <iostream>
#include <string>

using namespace std;

int main() {
    tuple<int, double, string> data(10, 20.4, "test data");

    //> method 1 : use std::get to retrieve data
    cout << "method 1" << endl;
    cout << "id : " << get<0>(data) << endl;
    cout << "value : " << get<1>(data) << endl;
    cout << "msg : " << get<2>(data) << endl << endl;

    //> method 2 : use std::tie to retrieve data
    int id;
    double value;
    string msg;

    tie(id, value, msg) = data;

    cout << "method 2" << endl;
    cout << "id : " << id << endl;
    cout << "value : " << value << endl;
    cout << "msg : " << msg << endl;

    return 0;
}

<Example 2> Used as function's return type

=> 把 tuple 當作 function 的 return type,就可以一次回傳多個值回來

#include <iostream>
#include <string>

using namespace std;

tuple<int, double, string> getData(int id) {
    if(id == 1) {
        return make_tuple(1, 199.7, "data whose id is 1");
    }
    else {
        return make_tuple(999, 10.1, "other data");
    }
}

int main() {
    auto myData1 = getData(1);

    cout << "id : " << get<0>(myData1) << endl;
    cout << "value : " << get<1>(myData1) << endl;
    cout << "msg : " << get<2>(myData1) << endl << endl;

    int id;
    double value;
    string msg;

    tie(id, value, msg) = getData(3);
    cout << "id : " << id << endl;
    cout << "value : " << value << endl;
    cout << "msg : " << msg << endl;

    return 0;
}

沒有留言:

張貼留言