您的位置:首页 > 其它

15 STL中容器双向链表list和单向链表forward_list

2017-11-20 23:19 1716 查看

1、概述

本篇及以下讲述STL容器不再具体详细示例,而是把该容器的特有性质用一段代码示例表示。容器list和forward_list也是属于sequence containers,其中list为双向链表,forword_list为单向链表。

2、双向链表list

1)数据结构

双向链表每个元素都是通过指针双向相连,结构如下:



2)声明list,向list添加元素

#include <list>
#include <cstdio> //_snprintf()
#include <algorithm> //find()
#include <ctime>
#include <iostream>
#include <string>
using namespace std;
using std::string;

list<string> c;
char buf[10];
srand((unsigned)time(NULL));
for (long i = 0; i < value; ++i){
_snprintf(buf, 10, "%d", rand());
c.push_back(string(buf));
}

注意点:

a、头文件先使用#include <list>,才能使用list容器;

b、使用push_back()函数向链表尾部添加元素,当然也可以使用push_front()方法。

2)对list进行元素查找和排序

list<string>::iterator ite;
ite = ::find(c.begin(), c.end(), target);//查找
if (ite != c.end()){
cout << "found, " << *ite << endl;
}
else{
cout << "not found! " << endl;
}
c.sort();//排序
注意点:

a、使用全局函数find()来查找元素;

b、使用内部的sort()函数来对list排序,而没有全局的sort()方法,因为全局方法中有对迭代器的相关操作,对list结构是不适合的,所以list容器本身定义了sort()方法。

3、单向链表forward_list

1)数据结构

单向链表forward_list也是通过指针相连,但是指针是单向的,且尾端是封闭的,不能进行相关操作:



2)声明forward_list,向容器添加元素

#include <forward_list>
#include <string>
#include <ctime>
#include <iostream>
using namespace std;
forward_list<string> c;
char buf[10];
srand((unsigned)time(NULL));
for (long i = 0; i < value; ++i){
_snprintf(buf, 10, "%d", rand());
c.push_front(string(buf));
}
注意点:

a、头文件使用#include <forward_list>;

b、通过push_front()方法向链表添加元素,没有push_back()方法。
3)对forward_list容器进行查找和排序

string target = get_a_target_string();
auto pItem = ::find(c.begin(), c.end(), target);
if (pItem != c.end()){
cout << "found, " << *pItem << endl;
}
else{
cout << "not found!" << endl;
}
c.sort();
注意点:

a、使用全局函数fing()进行元素查找;

b、使用容器成员函数进行forward_list的排序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: