Chapter 19 STL Containers

30
Chapter 19 STL Containers §19.1 STL Basics §19.2 STL Iterators §19.3 Sequence Containers §19.4 Associative Containers §19.5 Container Adapters

description

Chapter 19 STL Containers. §19.1 STL Basics §19.2 STL Iterators §19.3 Sequence Containers §19.4 Associative Containers §19.5 Container Adapters. §19.1 STL Basics. Standard Template Library ( STL ) 标准模板库 A software library included in the C++ Standard Library Purpose - PowerPoint PPT Presentation

Transcript of Chapter 19 STL Containers

Page 1: Chapter 19           STL Containers

Chapter 19 STL Containers

§19.1 STL Basics§19.2 STL Iterators§19.3 Sequence Containers§19.4 Associative Containers§19.5 Container Adapters

Page 2: Chapter 19           STL Containers

§19.1 STL Basics

Standard Template Library (STL) 标准模板库 A software library included in the C++ Standard Library

Purpose To standardize commonly used components

History Originally developed by Alexander Stepanov in 1980s Accepted as part of C++ standard in Feb. 1994

2

Page 3: Chapter 19           STL Containers

Three Components of STL Containers(容器)

A container object, such as vector, used to store a collection of data, often referred to as elements

Iterators(迭代器) Objects that facilitate traversing through the elements in

a container Like built-in pointers that provide a convenient way to

access and manipulate the elements in a container Algorithms(算法)

Functions to manipulate data such as sorting, searching, and comparing elements.

Most of them use iterators to access the elements in the container.

3

Page 4: Chapter 19           STL Containers

Three Types of Containers

Sequence/sequential containers, 序列容器 Represent linear data structures Three sequence containers

vector 向量 , list 表 , and deque 双端队列 Associative containers,关联容器 /联合容器

Non-linear containers that can locate elements stored in the container quickly

Four associative containers set 集合 , multiset 多重集合 , map 映射 , and multimap 多重映射

Container adapters,容器适配器 Constrained versions of sequence containers stack 栈 , queue 队列 , and priority_queue 优先队列

4

Page 5: Chapter 19           STL Containers

Container Classes

5

STL Container Header File Applications vector <vector> For direct access to any element, and quick insertion and deletion at the end of the vector.

deque <deque> For direct access to any element, quick insertion

and deletion at the front and end of the deque.

list <list> For rapid insertion and deletion anywhere.

set <set> For direct lookup, no duplicated elements.

multiset <set> Same as set except that duplicated elements allowed.

map <map> Key/value pair mapping, no duplicates allowed, and

quick lookup using the key.

multimap <map> Same as map, except that keys may be duplicated

stack <stack> Last-in/first-out container.

queue <queue> First-in/first-out container.

priority_queue <queue> The highest-priority element is removed first.

Page 6: Chapter 19           STL Containers

Common Functions to All Containers

6

Functions Description non-arg constructor Constructs an empty container.

constructor with args In addition to the non-arg constructor, every container

has several constructors with args.

copy constructor Creates a container by copying the elements from an

existing container of the same type.

destructor Performs cleanup after the container is destroyed.

empty() Returns true if there are no elements in the container.

size() Returns the number of elements in the container.

operator= Copies one container to another.

Relational operators The elements in the two containers are compared

(<, <=, >, >=, sequentially to determine the relation.

==, and !=)

Page 7: Chapter 19           STL Containers

Common Functions to Sequence/Associative Containers

7

Functions Description c1.swap(c2) Swap the elements of two containers c1 and c2.

c.max_size() Returns the maximum number of elements a container can hold.

c.clear() Erases all the elements from the container.

c.begin() Returns an iterator to the first element in the container.

c.end() Returns an iterator that refers to the next position after the

end of the container.

c.rbegin() Returns an iterator to the last element in the container for

processing the elements in reverse order.

c.rend() Returns an iterator that refers to the position before the

first element in the container

c.erase(beg, end) Erases the elements in the container from beg to end-1. Bothe

beg and end are iterators.

Page 8: Chapter 19           STL Containers

Simple Demo

Listing 19.1 gives a simple example that demonstrates how to create a vector, list, deque, set, multiset, stack, and queue.

8

SimpleSTLDemo Run

Page 9: Chapter 19           STL Containers

§19.2 STL Iterators

Iterators are objects to facilitate traversing through the elements in a container

A iterator is like a built-in pointer that can manipulate the elements in a container

9

IteratorDemo Run

element 1

begin()

… element 2 element n

end()

Pointers themselves are iterators. The array pointers can be treated as iterators.

Page 10: Chapter 19           STL Containers

Type of Iterators

Different containers may have different types of iterators

Five types: Input (Output) iterator

For reading/writing from/to container Moving only in forward direction

Forward iterator Combination of input/output iterator

Bidirectional iterator A forward iterator that can move backward

Random access iterator A bidirectional iterator that can jump

10

RandomAccess

Bidirectional

Forward

Input Output

Page 11: Chapter 19           STL Containers

Iterator Types Supported by Containers

11

STL Container Type of Iterators Supported vector random access iterators deque random access iterators

list bidirectional iterators

set bidirectional iterators

multiset bidirectional iterators

map bidirectional iterators

multimap bidirectional iterators

stack no iterator support

queue no iterator support

priority_queue no iterator support

Page 12: Chapter 19           STL Containers

Predefined Iterators

Iterators have been defined in every containers Using “typedef”

The typedefs of iterators iterator const_iterator reverse_iterator const_reverse_iterator

12

typedef int integer;integer value = 40;

ReverseIteratorDemoRun

ConstIteratorDemoRun

Page 13: Chapter 19           STL Containers

Iterator Operators

Using overloaded operators to manipulate the an iterator Move its position Access the element Compare with other iterators

13

Page 14: Chapter 19           STL Containers

14

Operator Description All iterators ++p Preincrement an iterator.

p++ Postincrement an iterator.

Input iterators

*p Dereference an iterator (used as rvalue).

p1 == p2 Evaluates true if p1 and p2 point to the same element.

p1 != p2 Evaluates true if p1 and p2 point to different elements.

Output iterators

*p Dereference an iterator (used as lvalue).

Bidirectionl iterators

--p Predecrement an iterator.

p-- Postdecrement an iterator.

Random-access iterators

p += i Increment iterator p by i positions.

p -= i Decrement iterator p by i positions.

p + i Returns an iterator ith position after p.

p - i Returns an iterator ith position before p.

p1 < p2 Returns true if p1 is before p2.

p1 <= p2 Returns true if p1 is before or equal to p2.

p1 > p2 Returns true if p1 is after p2.

p1 >= p2 Returns true if p1 is after p2 or equal to p2.

p[i] Returns the element at the position p offset by i.

Page 15: Chapter 19           STL Containers

Iterator Operator Demo

15

IteratorOperatorDemo Run

vector<int> intVector; intVector.push_back(10); intVector.push_back(20); intVector.push_back(30); intVector.push_back(40); intVector.push_back(50); intVector.push_back(60);

vector<int>::iterator p1 = intVector.begin(); for (; p1 != intVector.end(); p1++){ cout << *p1 << " "; } cout << endl << *(--p1) << endl; cout << *(p1 - 3) << endl; cout << p1[-3] << endl; *p1 = 1234; cout << *p1 << endl;

Page 16: Chapter 19           STL Containers

I/O Steam Iterators

Iterators can also be used to manipulate I/O streams input iterator and output iterator

16

InputOutputStreamIteratorDemo

Run

Page 17: Chapter 19           STL Containers

§19.3 Sequence Containers

Represent linear data structures

17

Headerfile

Strong points Weak points Impl. struct.

vector <vector> Random accessInserting and deleting at the end

Inserting/Deleting in the middle or front

array

deque <deque> Random accessInserting and deleting at the front and end

Inserting/Deleting in the middle

array

list <list> Inserting and deleting anywhere

Random access linkedlist

Page 18: Chapter 19           STL Containers

Common Functions in Sequence Container

18

Functions Description assign(n, elem) Assign n copies of the specified element in

the container.

assign(beg, end) Assign the elements in the range from iterator

beg to iterator end.

push_back(elem) Appends an element in the container.

pop_back() Removes the last element from the container.

front() Returns the reference of the first element.

back() Returns the reference of the last element.

insert(position, elem) Inserts an element at the specified iterator.

Page 19: Chapter 19           STL Containers

Sequence Container: vector

19

vector(n, element) vector(beg, end) vector(size) at(index)

Constructs a vector filled with n copies of the same element.

Constructs a vector initialized with elements from iterator beg to end.

Constructs a vector with the specified size. Returns the element at the specified index.

Functions Description

VectorDemo Run

An insert call may invalidate previously obtained iterators!

Page 20: Chapter 19           STL Containers

Sequence Container: deque

20

DequeDemo Run

deque(n, element) deque(beg, end) deque(size) at(index) push_front(element) pop_front()

Constructs a deque filled with n copies of the same element.

Constructs a deque initialized with elements from iterator beg to end.

Constructs a deque with the specified size. Returns the element at the specified index. Inserts the element to the front of the queue. Removes the element from the front of the queue.

Functions Description

An insert call may invalidate previously obtained iterators!

Page 21: Chapter 19           STL Containers

Sequence Container: list

21ListDemo Run

list(n, element) list(beg, end) list(size) push_front(element) pop_front(): dataType remove(element) remove_if(oper) splice(pos, list2) splice(pos1, list2, pos2)

splice(pos1, list2, beg, end)

sort() sort(oper) merge(list2) merge(list2, oper)

reverse()

Constructs a list filled with n copies of the same element.

Constructs a list initialized with elements from iterator beg to end.

Constructs a list initialized with the specified size. Inserts the element to the front of the queue. Removes the element from the front of the queue. Removes all the elements that are equal to the specified element. Removes all the elements for which oper(element) is true. All the elements of list2 are moved to this list before the specified

position. After invoking this function, list2 is empty. All the elements of list2 starting from pos2 are moved to this list

before pos1. After invoking this function, list2 is empty. All the elements of list2 from iterator beg to end are moved to this list

before pos1. After invoking this function, list2 is empty. Sorts the elements in the list in increasing order. Sorts the elements in the list. The sort criterion is specified by oper. Suppose the elements in this list and list2 are sorted. Merges list2 into

this list. After the merge, list2 is empty. Suppose the elements in this list and list2 are sorted based on sort

criterion oper. Merges list2 into this list. Reverse the elements in this list.

Functions Description

An insert call won’t change the previously obtained iterators!

Page 22: Chapter 19           STL Containers

§19.4 Associative Containers

Represent non-linear data structures Elements in an associative container are sorted

according to some sorting criterion (“<” by default) For fast storage and quick retrieval using keys

22

Headerfile

Strong points Weak points Impl. struct.

setmutlset <set>

For fast storage and quick retrieval using keys

Inserting/Deleting BST

mapmultimap

<map> For fast storage and quick retrieval using keys

Inserting/Deleting BST

Page 23: Chapter 19           STL Containers

Common Functions in Associative Containers

23

Functions Description find(key) Returns an iterator that points to the element with

the specified key in the container.

lower_bound(key) Returns an iterator that points to the first

element with the specified key in the container.

upper_bound(key) Returns an iterator that points to the next element

after the last element with the specified key in

the container.

count(key) Returns the number of occurrences of the element

with the specified key in the container.

Page 24: Chapter 19           STL Containers

Associative Containers: set and multiset

Mathematical set to store simple elements set and multiset are identical except that

multiset allows duplicate keys

24

SetDemo Run

Page 25: Chapter 19           STL Containers

Associative Containers: map and multimap

Storage of mapping from one data item (a key) to another (a value).

map and multimap are identical except that multimap allows duplicate keys

25

MapDemo Run

Page 26: Chapter 19           STL Containers

§19.5 Container Adapters

Containers adapted from the sequence containers For handling special cases

Programmer can choose an appropriate sequence container for a container adapter

26

Headerfile

Features Impl. struct.

stack <stack> Last-In-First-Out deque*, list, vector

queue <queue> First-In-First-Out deque*, list

priority_queue <queue> Largest-In-First-Out vector*, deque

*: default one

Page 27: Chapter 19           STL Containers

Container Adapter: stack

27

StackDemo Run

Functions Description push(element) Inserts the element to the top of the stack.

pop() Removes an element from the top of the stack.

top() Returns the top element from the stack without

removing it.

size() Returns the size of the stack.

empty() Returns true if the stack is empty.

Page 28: Chapter 19           STL Containers

Container Adapter: queue

28

QueueDemo Run

Functions Description push(element) Inserts the element to the top of the queue.

pop() Removes an element from the top of the queue.

front() Returns the front element from the queue

without removing it.

back() Returns the back element from the queue without

removing it.

size() Returns the size of the queue.

empty() Returns true if the queue is empty.

Page 29: Chapter 19           STL Containers

Container Adapter: priority_queue

29

PriorityQueueDemo Run

Page 30: Chapter 19           STL Containers

A Summary

Concepts STL, Container, Iterator, Algorithm Three types of containers

Features of different containers Syntax of declaring container objects Main functions of containers

30