C++ tuple元组的用法总结

2022年3月17日 下午10:27 分享 , ,

C++ tuple元组的用法总结

1.元组简介

用自己话说吧,两个变量捆绑的时候我们可以用pair,三个及以上的时候我们可以用结构体,这里在C++11里面有tuple可以用,理论上tuple可以有无数个任意类型的变量

2.tuple的创建的初始化

1)创建

tuple<int,string,bool> t1;
tuple<int,string,bool> t2(2022,"carry",true);
...
make_tuple(v1,v2);
{v1,v2};

2)引用

inline void Case_Test()
{
    int p=4;
    tuple<int,int&> t2(5,p);//第二个元素为p的引用
    cout<<get<1>(t2)<<endl;//4
    p=7;//p的值改变,t2的第二个值也改变
    cout<<get<1>(t2)<<endl;//7
    get<1>(t2)=10;//t2的第二个值改变,p的值也改变
    cout<<p<<endl;//10
}

3.tuple的操作

1)获取元素个数

tuple_size<decltype(mytuple)>::value

2)获取元素的值

用法:get<l_th>(obj)

解释:l_th是位置,obj是tuple名字

注意:可以做左值,也可以做右值,例如可以get<0>(t)=5;

tuple<int,int,int> t(1,2,3);
cout<<get<0>(t)<<" "<<get<1>(t)<<" "<<get<2>(t)<<endl;//1 2 3

特别注意:

tuple不支持迭代,只能通过元素索引(或tie解包)进行获取元素的值。但是给定的索引必须是在编译器就已经给定,不能在运行期进行动态传递,否则将发生编译错误:

编译错误:

for(int i=0; i<3; i++)
    std::cout << std::get<i>(mytuple) << " "; //将引发编译错误

3)获取元素类型

tuple_element<lth,decltype(obj)::type obj2

std::tuple<std::string, int> tp("Sven", 20);
// 得到第二个元素类型
std::tuple_element<1, decltype(tp)>::type ages;  // ages就为int类型
ages = std::get<1>(tp);
std::cout << "ages: " << ages << '\n';
//输出结果: 
ages: 20

4)tie解包

通过tie将tuple各个元素的值分贝赋值tie提供的四个变量中。

tuple<int,string,bool> t(2022,"carry",true);
int year;
string name;
bool chk;
tie(year,name,chk)=t;
cout<<year<<" "<<name<<" "<<chk<<endl;//2022 carry 1

如果其他不需要的话,那么就用std::ignore进行占位

tie(year,ignore,chk);//ignore占位

4.应用

给大家看看tuple在最小生成树里面的运用。

map<string,int> mp;
inline int find(int x)
{
    return fa[x]==x?x:fa[x]=find(fa[x]);
}
vector<tuple<int,int,int>> g;
bool cmp(tuple<int,int,int> x,tuple<int,int,int> y)
{
    return get<2>(x)<get<2>(y);//对第二个值,也就是w排序
}
inline void Case_Test()
{
    cin>>n>>m;
    for (int i=1;i<=n;i++) fa[i]=i;
    for (int i=1;i<=m;i++)
    {
        int u,v,w;
        cin>>u>>v>>w;
        g.push_back({u,v,w});//make_tuple(u,v,w);
    }
    sort(g.begin(),g.end(),cmp);
    for (auto &[u,v,w]:g)//C++17可以用
    {   
        int fu=find(u),fv=find(v);
        if (fu!=fv)
        {
            fa[fv]=fu;
            cnt++;
            ans+=w;
        }
        if (cnt==n-1) break;
    }
    cout<<ans;
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注