STL——容器(List)list 的大小操作
ist.size();
//返回容器中元素的个数
1 #include <iostream> 2 #include <list> 3 4 using namespace std; 5 6 int main() 7 { 8 int num[] = { 111,222,333,444,555 }; 9 list<int> listInt_A(num, num + size(num)); 10 11 cout << "容器中的元素数量为:" << listInt_A.size() << endl; 12 13 return 0; 14 }
打印结果:
list.empty();
//判断容器是否为空
1 #include <iostream> 2 #include <list> 3 4 using namespace std; 5 6 int main() 7 { 8 int num[] = { 111,222,333,444,555 }; 9 list<int> listInt_A(num, num + size(num)); 10 list<int> listInt_B; 11 12 if (listInt_A.empty()) //如果不为空将会返回false,如果为空返回 ture 13 { 14 cout << "listInt_A 容器为空" << endl; 15 } 16 else 17 { 18 cout << "listInt_A 容器不为空" << endl; 19 } 20 21 if (listInt_B.empty()) //如果不为空将会返回false,如果为空返回 ture 22 { 23 cout << "listInt_B 容器为空" << endl; 24 } 25 else 26 { 27 cout << "listInt_B 容器不为空" << endl; 28 } 29 30 return 0; 31 }
打印结果:
list.resize(num);
//重新指定容器的长度为num,若容器变长,则以默认值0填充新位置。如果容器变短,则末尾超出容器长度的元素被删除
1 #include <iostream> 2 #include <list> 3 4 using namespace std; 5 6 int main() 7 { 8 int num[] = { 111,222,333,444,555 }; 9 list<int> listInt_A(num, num + size(num)); 10 11 cout << "resize 前遍历 listInt_A:" << endl; 12 for (list<int>::iterator it = listInt_A.begin(); it != listInt_A.end(); it++) 13 { 14 cout << *it << " "; 15 } 16 cout << endl; 17 18 //使用 resize 重新指定容器长度 19 listInt_A.resize(9); 20 cout << "resize 扩充至9个元素后遍历 listInt_A:" << endl; 21 for (list<int>::iterator it = listInt_A.begin(); it != listInt_A.end(); it++) 22 { 23 cout << *it << " "; 24 } 25 cout << endl; 26 27 //使用 resize 重新指定容器长度 28 listInt_A.resize(3); 29 cout << "resize 删减至3个元素后遍历 listInt_A:" << endl; 30 for (list<int>::iterator it = listInt_A.begin(); it != listInt_A.end(); it++) 31 { 32 cout << *it << " "; 33 } 34 cout << endl; 35 36 return 0; 37 }
打印结果:
list.resize(num, elem);
//重新指定容器的长度为num,若容器变长,则以elem值填充新位置。如果容器变短,则末尾超出容器长度的元素被删除
1 #include <iostream> 2 #include <list> 3 4 using namespace std; 5 6 int main() 7 { 8 int num[] = { 111,222,333,444,555 }; 9 list<int> listInt_A(num, num + size(num)); 10 11 cout << "resize 前遍历 listInt_A:" << endl; 12 for (list<int>::iterator it = listInt_A.begin(); it != listInt_A.end(); it++) 13 { 14 cout << *it << " "; 15 } 16 cout << endl; 17 18 //使用 resize 重新指定容器长度 19 listInt_A.resize(9, 888); 20 cout << "resize 扩充至9个元素后遍历 listInt_A:" << endl; 21 for (list<int>::iterator it = listInt_A.begin(); it != listInt_A.end(); it++) 22 { 23 cout << *it << " "; 24 } 25 cout << endl; 26 27 //使用 resize 重新指定容器长度 28 listInt_A.resize(3); 29 cout << "resize 删减至3个元素后遍历 listInt_A:" << endl; 30 for (list<int>::iterator it = listInt_A.begin(); it != listInt_A.end(); it++) 31 { 32 cout << *it << " "; 33 } 34 cout << endl; 35 36 return 0; 37 }
打印结果:
=====================================================================================================================