喜歡這篇文章嗎?喜歡的話去看博主的置頂博客,即可依據分類找到此文章的原版得到更好的體驗,
圖片及代碼顯示的問題,筆者深感抱歉,想要更好的體驗去原博文即可。
title: Boost學習筆記3 - Boost::Tuple
mathjax: true
date: 2020-03-17 18:13:25
categories: [c++筆記,Boost學習筆記]
tags: [c++筆記,Boost學習筆記]
keywords: [c++筆記,Boost學習筆記]
Boost::Tuple
boost::tuple是一個元組。在c++11被編入STL
第六行無法通過編譯,這說明tuple的長度最長只能是10
第9-12行定義了3個元組
第13行演示瞭如何通過make_tuple構造元組
第14行演示瞭如何通過get來訪問元組裏面的元素
第16行演示了get的返回值是引用
第19-20行演示了tuple的等號操作
第23-27行演示了tuple中可以儲存引用
第28行通過tie構造了一個全引用元組
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
#include <boost/tuple/tuple_io.hpp>
#include <bits/stdc++.h>
// boost::tuple<int, int, int, int, int, int, int, int, int, int, int>too_long;
int main() {
// 基本操作
boost::tuple<int, int, int, int, int, int, int, int, int, int> a(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
boost::tuple<std::string, std::string> b("hello", "world");
boost::tuple<std::string, std::string> c("hello", "world2");
std::cout << boost::make_tuple(1, 2, 3, 4) << std::endl;
std::cout << "a.get<0>() is " << a.get<0>() << std::endl;
std::cout << "a is " << a << std::endl;
a.get<0>() = -1;
std::cout << "a is " << a << std::endl;
std::cout << "b is " << b << std::endl;
std::cout << "b==c is " << (b == c) << std::endl;
std::cout << "b==b is " << (b == b) << std::endl;
// 進階操作
int x = 1, y = 2;
boost::tuple<int&, int> reference(boost::ref(x), y);
// boost::tuple<int&, int> reference(x, y); 也可以
x = 5;
std::cout << "reference is " << reference << std::endl;
auto reference2 = boost::tie(x, y);
x = 10, y = 11;
std::cout << "reference2 is " << reference2 << std::endl;
}
輸出
(1 2 3 4)
a.get<0>() is 1
a is (1 2 3 4 5 6 7 8 9 10)
a is (-1 2 3 4 5 6 7 8 9 10)
b is (hello world)
b==c is 0
b==b is 1
reference is (5 2)
reference2 is (10 11)