stl学习记录(2)

时间:2025-05-12 23:07:50
#include <iostream>
#include <utility>
#include <tuple>
#include <complex>
#include <string> using namespace std; // 代码 改编自 C++标准库——自学教程与参考手册 英文第二版 //====================================
// tuple io
template <int IDX,int MAX,typename... Args>
struct PRINT_TUPLE{
static void print(ostream& strm, const tuple<Args...>& t){
strm << get<IDX>(t) << (IDX + == MAX ? "" : ",");
PRINT_TUPLE<IDX + , MAX, Args...>::print(strm,t);
}
}; template <int MAX,typename... Args>
struct PRINT_TUPLE<MAX, MAX, Args...>{
static void print(ostream& strm, const tuple<Args...>& t){
}
}; template <typename... Args>
ostream& operator << (ostream& strm,
tuple<Args...>& t)
{
strm << "[";
PRINT_TUPLE<, sizeof...(Args), Args...>::print(strm,t);
return strm << "]";
} //==================================== class Foo{
public:
Foo(tuple<int, float>){
cout << "Foo::Foo(tuple)" << endl;
} template <typename... Args>
Foo(Args... args){
cout << "Foo::Foo(atgs...)" << endl;
}
}; int _tmain(int argc, _TCHAR* argv[])
{
// cpp11 后 一些新语法 在STL中得使用
tuple<int, double>t(,2.22); pair<int, Foo>p1(, t); pair<int, Foo>p2(piecewise_construct, make_tuple(), t); // 使用 ref() 表示对变量的引用
int i = ;
auto p = make_pair(ref(i), ref(i)); // 创建 pair<int&,int&>
++p.first;
++p.second;
cout << "i = " << i << endl; // tie() 演示
pair<char, char> q = make_pair('c','b');
char c;
tie(ignore, c) = q; // char c == 'b' //
tuple<string, int, int, complex<double>> tt;
tuple<int, double,string> t1(,6.3,"nico"); cout << get<>(t1) << " ";
cout << get<>(t1) << " ";
cout << get<>(t1) << " ";
cout << endl; auto t2 = make_tuple(,,"nico");
get<>(t1) = get<>(t2);
t1 = t2; // tuple io
tuple <int, double, string> iot(, 1.1, "more light");
cout << "io: " << iot << endl; return ;
}

cpp11stl的例子 VS2013下编译 通过

stl序列容器例子 
cpp11  vs2013下编译 通过

#include <memory>
#include <vector>
#include <array>
#include <string>
#include <list>
#include <iostream>
#include <functional>
#include <forward_list> using namespace std; int _tmain(int argc, _TCHAR* argv[])
{
array<string, > arrcoll = { "hello", "world" };
for (auto elem : arrcoll)
{
cout << elem << ' ';
}
cout << endl; list<char> listcoll;
for (char c = 'a'; c <= 'z'; ++c)
{
listcoll.push_back(c);
} for (auto elem : listcoll)
{
cout << elem << ' ';
}
cout << endl; //createforward-listcontainerforsomeprimenumbers
forward_list<long> coll = { , , , , , , };
//resizetwotimes
//-note:poorperformance
coll.resize();
coll.resize(, );
//printallelements:
for (auto elem : coll) {
cout << elem << ' ';
}
cout << endl; return ;
}