1. 程式人生 > 其它 >list容器的大小操作

list容器的大小操作

技術標籤:stl學習之listc++連結串列

大小操作

在這裡插入圖片描述

#include<iostream>
using namespace std;
#include<list>
//防止資料修改,只做讀取操作
void print(const list<int>& L)
{
	for (list<int>::const_iterator it = L.begin(); it != L.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
} //list的大小操作 void test() { //預設構造 list<int> L1 = {5,2,0,1}; L1.push_back(3); L1.push_back(1); L1.push_back(4); print(L1); //判斷容器是否為空 if (L1.empty()) { cout << "容器為空!" << endl; } else { cout << "容器不為空" << endl; cout << "容器中元素個數:"
<< L1.size() << endl; } //重新指定大小,如果新指定大小大於原來的元素個數,就用預設值0填充新位置 L1.resize(10); print(L1); //如果指定大小小於原來的元素個數,就講多出的元素刪除 L1.resize(3); print(L1); //可以用resize的過載版本,自己指定多出來的新位置的預設值 L1.resize(6,521); print(L1); } int main() { test(); system("pause"); return 0; }