多年前, 去某公司面试, 被问过list和vector, 鉴于之前我们学习过vector, 在本文中, 我们只简要介绍一下list. 我不打算全面介绍list, 因为那是手册应该做的, 下面, 让我们来窥探一下与list相关的小程序吧:
#pragma warning(disable: 4786) // 去掉相关warning
#include <list>
#include <string>
#include <iostream>
#include <algorithm> // for_each 等
using namespace std;
void printString (string& s)
{
cout << s << endl;
}
int main ()
{
list<string> stringList; // list是类模板, list<string>是类, stringList是对象
if(stringList.empty()) // 判断stringList是否为空
{
cout << "empty" << endl;
}
cout << endl;
if(stringList.begin() == stringList.end()) // 判断stringList是否为空
{
cout << "empty" << endl;
}
cout << endl;
stringList.push_back("hello"); // 加在链表尾
stringList.push_back("world"); // 加在链表尾
stringList.push_front("c++"); // 加在链表头
stringList.push_front("hello"); // 加在链表头
list<string>::iterator it;
for(it = stringList.begin(); it != stringList.end(); it++) // 遍历
{
cout << *it << endl;
}
cout << endl;
for_each(stringList.begin(), stringList.end(), printString); // 遍历
cout << endl;
cout << count(stringList.begin(), stringList.end(), "hello") << endl; // 计算hello的个数
cout << endl;
it = find(stringList.begin(), stringList.end(), "helloxyz"); // 查找是否有helloxyz
if (stringList.end() == it)
{
cout << "no" << endl;
}
else
{
cout << *it << endl;
}
cout << endl;
stringList.sort(); // 排序
for_each(stringList.begin(), stringList.end(), printString);
cout << endl;
stringList.insert(stringList.begin(), "c"); // 插在链表头
for_each(stringList.begin(), stringList.end(), printString);
cout << endl;
stringList.insert(stringList.end(), "zzz"); // 插在链表尾巴
for_each(stringList.begin(), stringList.end(), printString);
cout << endl;
stringList.insert(--stringList.end() , "yyy"); // 插在链表倒数第二的位置
for_each(stringList.begin(), stringList.end(), printString);
cout << endl;
stringList.remove("hello"); // 去掉hello
for_each(stringList.begin(), stringList.end(), printString);
cout << endl;
stringList.pop_front(); // 删除头
for_each(stringList.begin(), stringList.end(), printString);
cout << endl;
stringList.pop_back(); // 删除尾
for_each(stringList.begin(), stringList.end(), printString);
cout << endl;
stringList.reverse(); // 逆置
for_each(stringList.begin(), stringList.end(), printString);
cout << endl;
return 0;
}
结果为:
empty
empty
hello
c++
hello
world
hello
c++
hello
world
2
no
c++
hello
hello
world
c
c++
hello
hello
world
c
c++
hello
hello
world
zzz
c
c++
hello
hello
world
yyy
zzz
c
c++
world
yyy
zzz
c++
world
yyy
zzz
c++
world
yyy
yyy
world
c++
至于list的其他用法, 网上资料到处都是。 在此, 我们仅仅进行热身活动。