深入应用C++11 笔记(四)
第一章 程序简洁之道
1.8 tupe元组
构造tuple
//头文件为: <tuple> 使用make_tuple 构造一个tuple char* sendPack; int nSendSize; tuple<const char*, int> tp = make_tuple(sendPack, nSendSize); //使用std::tie构造 tuple<const char*, int> tp1 = std::tie(sendPack, nSendSize); //这个tuple和下面的结构体等价 struct tp { char* p; int len; }
用tuple<const char*,int> 就可以创建这个结构体,而作用是一样的。
获取tuple的值
const char* data = std::get<0>(tp);//获取上第一个值 int len = std::get<1>(tp);//获取第二个值
也可以通过std::tie解包tuple
std::string str; int len; std::tie(str,len) = tp;
解包时,我们如果只想解某个位置的值时,可以用std::ignore占位符来表示不解某个位置的值
std::tie(str,std::ignore) = tp;
通过tuple_cat连接多个tuple (C++ 14 !!!)
std::tuple<int, std::string, float> t1(10, "Test", 3.14); int n = 7; auto t2 = std::tuple_cat(t1, std::make_pair("Foo", "bar"), t1, std::tie(n)); n = 10; //t2:(10, Test, 3.14, Foo, bar, 10, Test, 3.14, 10)
遍历tuple (详见cppreference)
#include <iostream> #include <tuple> #include <string> // helper function to print a tuple of any size template<class Tuple, std::size_t N> struct TuplePrinter { static void print(const Tuple& t) { TuplePrinter<Tuple, N-1>::print(t); std::cout << ", " << std::get<N-1>(t); } }; template<class Tuple> struct TuplePrinter<Tuple, 1> { static void print(const Tuple& t) { std::cout << std::get<0>(t); } }; template<class... Args> void print(const std::tuple<Args...>& t) { std::cout << "("; TuplePrinter<decltype(t), sizeof...(Args)>::print(t); std::cout << ")\n"; } // end helper function int main() { std::tuple<int, std::string, float> t1(10, "Test", 3.14); int n = 7; auto t2 = std::tuple_cat(t1, std::make_pair("Foo", "bar"), t1, std::tie(n)); n = 10; print(t2); } //(10, Test, 3.14, Foo, bar, 10, Test, 3.14, 10)
1.9 列表初始化返回值
C++11 的标准规定,函数可以返回花括号包围的值的列表。
vector<string> fun(bool isempty)
{
if (isempty)
{
return{};
}
else
{
return{ "abc","def","ghi" };
}
}
int main()
{
vector<string> ret = fun(false);
vector<string> ret1 = fun(true);
return 0;
}