C++ Tuple::tie() 函式



C++ 的std::tuple::tie()函式用於幫助將多個變數繫結到元組的元素。本質上,它允許將元組值直接解包到指定的變數中。它主要用於您希望將元組的元素分解成單獨的變數以進行進一步操作的場景。

tie() 函式可以與其他操作(如比較和排序)結合使用。

語法

以下是 std::tuple::tie() 函式的語法。

tie( Types&... args ) noexcept;

引數

  • args - 它包含構造的元組應包含的元素列表。

示例

讓我們看下面的例子,我們將使用 tie() 和 make_tuple() 交換兩個變數的值。

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    int x = 11, y = 111;
    tie(x, y) = make_tuple(y, x);
    cout << "x: " << x << ", y: " << y << endl;
    return 0;
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

x: 111, y: 11

示例

考慮另一種情況,我們將使用 tie() 函式將元組資料解包到單獨的變數中。

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    tuple<float, string> data = make_tuple(0.01, "Welcome");
    float x;
    string y;
    tie(x,y) = data;
    cout << "x: " << x << ", y: " << y <<endl;
    return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

x: 0.01, y: Welcome

示例

在下面的示例中,元組資料的第二個元素僅解包到變數中,而其他元素被忽略。

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    tuple<int, string> data = make_tuple(42, "TutorialsPoint");
    string x;
    tie(ignore, x) = data;
    cout << "x: " << x << endl;
    return 0;
}

輸出

以下是上述程式碼的輸出:

x: TutorialsPoint
廣告