我是靠谱客的博主 诚心大门,最近开发中收集的这篇文章主要介绍std::tuple、std::pair用法记录,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

std::pair

Microsoft C++ pair 结构

int main( )
{
   using namespace std;

   pair <int, double> a1;
   //直接查询值
   a1.first = 2;
   auto v1 = a1.second;

   //tie解包
   int v1;
   double v2
   tie(v1, v2) = a1;
   tie(v1, std::ignore) = a1;//不解包std::ignore
   //Structured Binding解包
   auto[va1, va2] = a1;

   // Using the constructor to declare and initialize a pair
   pair <int, double> p1 ( 10, 1.1e-2 );

   // Compare using the helper function to declare and initialize a pair
   pair <int, double> p2;
   p2 = make_pair ( 10, 2.22e-1 );

   // Making a copy of a pair
   pair <int, double> p3 ( p1 );

   auto p4 = p3;

   // 交换
   p4.swap(a1);

   auto p5 = make_pair<int, double> ( 15, 25.5 );

   //与std::map
   map <int, int> m1;
   m1.insert ( pair <int, int> ( 1, 10 ) );
   m1.insert ( pair <int, int> ( 2, 20 ) );
}

std::tuple

Microsoft C++ <tuple>

初始化

#include <tuple>
using namespace std;
typedef tuple <int, double, string> ids;

int main()
{
     // 无参构造
     ids t1;

     // Using the constructor to declare and initialize a tuple
     ids p1(10, 1.1e-2, "one");

     // Compare using the helper function to declare and initialize a tuple
     ids p2;
     p2 = make_tuple(10, 2.22e-1, "two");

     // Making a copy of a tuple
     ids p3(p1);

     auto t2 = make_tuple<int, double, string>(0, 1.1, "123");

     // tie 初始化
     int a1 = 0;
     float a2 = 0.1f;
     int a3 = 0;
     auto t3 = tie(a1, a2, a3);

     // forward_as_tuple 初始化
     auto t4 = forward_as_tuple(a1, a2, a3);
}

获取值

//get
void print_ids(const ids& i)
{
   cout << "( "
        << get<0>(i) << ", "
        << get<1>(i) << ", "
        << get<2>(i) << " )." << endl;
}

//tie解包
auto t1 = make_tuple<int, double, string>(0, 1.1, "123");
int vt1;
double vt2;
string vt3;
tie(vt1, std::ignore, vt3) = t1;

//Structured Binding解包
auto [vt11, vt21, vt31] = t1;

获取tuple的数量

auto t1 = make_tuple<int, double, string>(0, 1.1, "123");
size_t tNum = tuple_size<decltype(t1)>::value;

拼接

std::tuple<int, int, int> t5 = {1, 2, 3};
std::tuple<int, int, int> t6 = {1, 2, 3};
std::tuple<int, int, int, int, int, int> t7 = tuple_cat(t5, t6);

apply(C++17)

将一个tuple直接解构,用于函数的参数,从而完成函数的调用,std::pair同样适用

int getAdd(int a1, int a2, int a3)
{
    return a1 + a2 + a3;
}

std::tuple<int, int, int> addArg {1, 2, 3};
std::cout << std::apply(getAdd, addArg) << std::endl;

最后

以上就是诚心大门为你收集整理的std::tuple、std::pair用法记录的全部内容,希望文章能够帮你解决std::tuple、std::pair用法记录所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部