当前位置: 首页 > 工具软件 > tie > 使用案例 >

C++:tuple的解包tie【tuple<std::string, int, int> tp;tie(name, ages, areaCode) = tp】

武睿
2023-12-01

如同pair一样也是可以通过tie进行解包tuple的各个元素的值。如下tuple对象有4个元素,通过tie解包将会把这4个元素的值分别赋值给tie提供的4个变量中。

#include <iostream>
#include <tuple>
#include <utility>
 
int main(int argc, char **argv) {
    std::tuple<std::string, int, std::string, int> tp;
    tp = std::make_tuple("Sven", 25, "Shanghai", 21);
 
    // 定义接收变量
    std::string name;
    std::string addr;
    int ages;
    int areaCode;
 
    std::tie(name, ages, addr, areaCode) = tp;
    std::cout << "Output: " << '\n';
    std::cout << "name: " << name <<", ";
    std::cout << "addr: " << addr << ", ";
    std::cout << "ages: " << ages << ", ";
    std::cout << "areaCode: " << areaCode << '\n';
 
    return 0;
}
 
//输出结果:
Output: 
name: Sven, addr: Shanghai, ages: 25, areaCode: 21

C++ tuple元组的基本用法(总结)_sevencheng798的博客-CSDN博客_c++ tuple赋值

 类似资料: