#include <iostream> #include <list> #include <vector> #include <string> #include <deque> #include <forward_list> #include <array> using namespace std; int main(){ //test1 容器的初始化 /* list<string> au = {"MM","DD","YY"}; vector<const char*> arti = {"a","b","c"}; list<string> li(au); //deque<string> de(au);//錯誤:容易類型不匹配 //vector<string> v(arti);//錯誤:容易類型不匹配 deque<string> de(au.begin(), au.end()); deque<string> d2(arti.cbegin(), arti.cend()); vector<string> v1(au.begin(), au.end()); vector<string> v2(arti.cbegin(), arti.cend()); forward_list<string> f1(au.begin(),au.end()); list<string> l(5,"aa");//包含5個"a" forward_list<int> iv(10);//包含10個0; deque<string> d(3);//包含3個空string */ //test2 標準庫array的初始化 //標準庫array的大小屬於類型的一部分,內置數組不能夠賦值和拷貝,可是array能夠 /* array<int,5> a1; array<string,3> a2; array<int,5>::size_type i; //array<int>::size_type j;//錯誤,沒有提供數組的大小 array<int,4> a3 = {1,2,3,4}; array<int,3> a4 = {1};//a4[0]爲1,其他爲0 for(auto s : a4){ cout << s << " "; } cout << endl; int ia[] = {1,2,3}; //int cpy[3] = ia;//錯誤 array<int, 3> ia2 = {1}; array<int, 3> ia3 = ia2; ia3 = {3,4};//ia3變成3,4,0 for(auto s : ia3){ cout << s << " "; } cout << endl; //array<int, 3> ia4(ia);//錯誤 //array<int, 3> ia5 = ia;//錯誤 */ //test3 容器的賦值 //assign的做用:先清空容器裏全部的元素,再把新的元素添加進去 /* list<string> li; vector<char*> ol; //li = ol;//錯誤,容器類型不匹配 li.assign(ol.cbegin(), ol.cend()); list<string> l2(3, "aa"); l2.assign(2,"bb"); for(auto const s : l2){ cout << s << " "; } cout << endl; */ //test4 容器的swap //swap不交換容器裏的元素,只是交換兩個容器內部的數據結構 /* list<int> l1(3,10); list<int> l2(4,9); swap(l1, l2); for(auto const &s : l1){ cout << s << " "; } cout << endl; for(auto const &s : l2){ cout << s << " "; } cout << endl; */ //test5 容器的比較(==,!=,>,>=,<,<=) //是否可使用比較運算符,取決於容器裏的元素是否重寫了這個運算符 vector<int> v1 = {1,3,5,7,9,12}; vector<int> v2 = {1,3,9}; vector<int> v3 = {1,3,5,7}; vector<int> v4 = {1,3,5,7,9,12}; cout << (v1 < v2) << endl;//true cout << (v1 < v3) << endl;//false cout << (v1 == v4) << endl;//true cout << (v1 == v2) << endl;//false class Test{}; list<Test> l1(2); list<Test> l2(3); //cout << (l1 < l2) << endl;//錯誤,類Test沒有重寫<方法,全部沒法比較 return 0; }
<font color="green">ios
</font>c++