C++_3——库(tuple)
这一系列文章的目的是在学习了C++基础后,继续补充一些C++基础和进阶的知识点,包括C++11的相关内容。
以C++11标准为基础。
C++网站:http://www.cplusplus.com/reference/
- tuple类似于C语言的结构体,tuple访问成员不用变量名而是变量顺序,tuple内的变量类型可不同
- 基本使用
#include <tuple> // 构造 std::tuple<int,char> first; // default std::tuple<int,char> second (first); // copy std::tuple<int,char> third (std::make_tuple(20,'b')); // move std::tuple<long,char> fourth (third); // implicit conversion std::tuple<int,char> fifth (10,'a'); // initialization std::tuple<int,char> sixth (std::make_pair(30,'c')); // from pair / move // std::make_tuple auto first = std::make_tuple (10,'a'); // tuple < int, char > const int a = 0; int b[3]; // decayed types: auto second = std::make_tuple (a,b); // tuple < int, int* > auto third = std::make_tuple (std::ref(a),"abc"); // tuple < const int&, const char* > // std::tie int myint; char mychar; std::tuple<int,float,char> mytuple; mytuple = std::make_tuple (10, 2.6, 'a'); // packing values into tuple std::tie (myint, std::ignore, mychar) = mytuple; // unpacking tuple into variables // std::get 这里返回的是元素的引用 std::tuple<int,char> mytuple (10,'a'); std::get<0>(mytuple) = 20; std::cout << std::get<0>(mytuple) << " and " << std::get<1>(mytuple); // 20 and a // std::tuple_cat 串联不同的tuple std::tuple<float,std::string> mytuple (3.14,"pi"); std::pair<int,char> mypair (10,'a'); auto myauto = std::tuple_cat ( mytuple, std::tuple<int,char>(mypair) );
- 其他
- std::ref与std::cref的使用,参见这篇博客
std::ref为引用传递,std::cref为const引用传递 - std::ignore
一方面是作为std::tie的占位符,另一方面还可以避免一些未使用函数返回值的warning,如下,nodiscard用于提示这个函数的返回值很重要,不应丢弃,一旦丢弃则发出自定义的字符串以警告(“important…info output”),但如果使用std::ignore,则没有警告。
#include <tuple> [[nodiscard("important...info output")]] int dontIgnoreMe(){ return 42; } int main(){ std::ignore = dontIgnoreMe(); }
**注. nodiscard是C++17的内容
- std::ref与std::cref的使用,参见这篇博客