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

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的排序。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值