c++list的使用方法
/*首先我是c語言的愛好者,之前沒接觸過c++,現在開始學習c++,因此總會和c語言進行對比,所謂的容器,其實就是鏈表的!在c語言數據結構中有所提及,c++把其進行封裝成了庫,不需要像以前學習數據結構那樣具體去實現,只要學院、會調用就可以了。
*/
#include "stdafx.h"
#include <iostream>
#include <list>
#include <windows.h>
using namespace std;
typedef list<int> INTLIST; //定義一個數列INTLIST,下一次遇見他的時候就會可以等價一個數組或者是一個容器或者是一個叠代器。
//從前向後顯示list隊列的全部元素
void put_list(INTLIST list, char *name)
{
INTLIST::iterator plist;
cout << "The contents of " << name << " : ";
for (plist = list.begin(); plist != list.end(); plist++)
cout << *plist << " ";
cout << endl;
}
//測試list容器的功能
void main(void)
{
//list1對象初始為空
INTLIST list1;
INTLIST list2(5, 1);
INTLIST list3(list2.begin(), --list2.end());
//聲明一個名為i的雙向叠代器
INTLIST::iterator i;
put_list(list1, "list1"); //print the lists
put_list(list2, "list2");
put_list(list3, "list3");
list1.push_back(7); //mask the lseven num put out
list1.push_back(8);
cout << "list1.push_back(7) and list1.push_back(8):" << endl;
put_list(list1, "list1");
list1.push_front(6); //把第一個元素6壓入第一個元素內
list1.push_front(5);
cout << "list1.push_front(6) and list1.push_front(5):" << endl;
put_list(list1, "list1");
list1.insert(list1.begin(), 3, 9); //list1的首位直添加3個9.
cout << "list1.insert(list1.begin()+1,3,9):" << endl;
put_list(list1, "list1");
//測試引用類函數
cout << "list1.front()=" << list1.front() << endl;
cout << "list1.back()=" << list1.back() << endl;
list1.pop_front();
list1.pop_back();
cout << "list1.pop_front() and list1.pop_back():" << endl;
put_list(list1, "list1");
list1.erase(++list1.begin());//擦出第一個元素
cout << "list1.erase(++list1.begin()):" << endl;
put_list(list1, "list1");
list2.assign(8, 1);
cout << "list2.assign(8,1):" << endl;
put_list(list2, "list2");
cout << "list1.max_size(): " << list1.max_size() << endl;
cout << "list1.size(): " << list1.size() << endl;
cout << "list1.empty(): " << list1.empty() << endl;
put_list(list1, "list1");
put_list(list3, "list3");
cout << "list1>list3: " << (list1 > list3) << endl;
cout << "list1<list3: " << (list1 < list3) << endl;
list1.sort();
put_list(list1, "list1");
list1.splice(++list1.begin(), list3);
put_list(list1, "list1");
put_list(list3, "list3");
Sleep(10000);
}
c++list的使用方法