List容器用法操作實(shí)例
// Test_20110513_1756.cpp : Defines the entry point for the console application.
//
//////////////////////////////////////////////////////////////////////////
//* list容器測試
//////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <list>
#include <iostream>
using namespace std;
typedef list<int> LISTINT;
int _tmain(int argc, _TCHAR* argv[])
{
//創(chuàng)建一個(gè)list容器
LISTINT lInt;
//在list容器的末尾,添加元素
cout << "------------------------------------------------" << endl << "操作:從后面添加元素" << endl;
for (LISTINT::value_type iValCount = 1; iValCount != 11; iValCount++)
lInt.push_back(iValCount);
for (LISTINT::iterator iter = lInt.begin(); iter != lInt.end(); iter++)
cout << *iter << endl;
//在list容器的頭部,添加元素
cout << "------------------------------------------------" << endl << "操作:從前面添加元素" << endl;
for (LISTINT::value_type iValCount = 11; iValCount != 21; iValCount++)
lInt.push_front(iValCount);
for (LISTINT::iterator iter = lInt.begin(); iter != lInt.end(); iter++)
cout << *iter << endl;
//取出最后一個(gè)元素
cout << "------------------------------------------------" << endl << "操作:取出最后一個(gè)元素" << endl;
cout << lInt.back() << endl;
//取出最前一個(gè)元素
cout << "------------------------------------------------" << endl << "操作:取出最前一個(gè)元素" << endl;
cout << lInt.front() << endl;
//從后向前顯示list中的元素(注意:迭代器,不可以同名,雖然在不同的作用域下)
cout << "------------------------------------------------" << endl << "操作:從后向向前顯示list中的元素" << endl;
for (LISTINT::reverse_iterator iter2 = lInt.rbegin(); iter2 != lInt.rend(); iter2++)
cout << *iter2 << endl;
//刪除一個(gè)元素
cout << "------------------------------------------------" << endl << "操作:刪除最后一個(gè)元素" << endl;
if (lInt.size() > 0)
{
LISTINT::iterator delIter = lInt.end();
delIter--;
cout << *delIter << endl;
lInt.erase(delIter);
if (lInt.size() > 0)
{
delIter = lInt.end();
delIter--;
cout << *delIter << endl;
}
}
//清空元素(并輸入所有元素內(nèi)容----正常輸出為空。因?yàn)楸磺蹇樟?
cout << "------------------------------------------------" << endl << "操作:清空所有元素(并輸入所有元素內(nèi)容----正常輸出為空。因?yàn)楸磺蹇樟?" << endl;
lInt.clear();
for (LISTINT::iterator iter3 = lInt.begin(); iter3 != lInt.end(); iter3++)
cout << *iter3 << endl;
//所有操作均已經(jīng)結(jié)束
cout << "------------------------------------------------" << endl << "操作:所有操作均已經(jīng)結(jié)束" << endl;
cout << "------------------------------------------------" << endl;
return 0;
}