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的排序。
相关文章推荐
- C++ STL 容器技术 之 list双向链表容器
- C++ STL学习笔记四 list双向链表容器
- STL--> list 双向循环链表容器 接口使用及介绍。 模拟实现 STL list容器
- STL(九)slist单向链表容器
- [C++ 从入门到放弃-07]C++STL之list双向链表容器
- C++ STL 容器技术 之 list双向链表容器
- C++ STL学习笔记四 list双向链表容器
- STL之list双向链表容器入门
- C++ STL 容器技术 之 list双向链表容器
- C++STL之list双向链表容器
- stl之list双向链表容器应用基础
- STL(八)list双向链表容器
- STL-forward_list(单向链表)
- STL泛型编程-list双向链表容器
- stl之list双向链表容器应用基础
- 双向链表容器list的头部、尾部、中间的插入
- list双向链表容器
- 容器第四课,JDK源代码分析,自己实现LinkedList,双向链表的概念_节点定义
- C++ 标准模板库STL 双向链表 list 使用方法与应用介绍(一)
- 【STL】STL之顺序容器:vector、deque、list、forward_list、array、string