stl

30
CSCI 3110 C++ STL

Upload: suganya-selvaraj

Post on 19-Jul-2016

7 views

Category:

Documents


3 download

DESCRIPTION

Standard template library

TRANSCRIPT

CSCI 3110

C++ STL

STL – Standard Template LibraryCollections of useful classes for common data

structuresAbility to store objects of any type (template)Study of containersContainers form the basis for treatment of data

structuresContainer – class that stores a collection of dataSTL consists of 10 container classes:

Sequence containersAdapter containersAssociative containers

STL ContainersSequence Container

Stores data by position in linear order:First element, second element , etc:

Associate ContainerStores elements by key, such as name, social

security number or part numberAccess an element by its key which may bear no

relationship to the location of the element in the container

Adapter ContainerContains another container as its underlying

storage structure

STL ContainersSequence Container

VectorDequeList

Adapter ContainersStackQueuePriority queue

Associative ContainerSet, multisetMap, multimap

Vector ContainerGeneralized array that stores a collection of

elements of the same data typeVector – similar to an array

Vectors allow access to its elements by using an index in the range from 0 to n-1 where n is the size of the vector

Vector vs arrayVector has operations that allow the

collection to grow and contract dynamically at the rear of the sequence

Vector ContainerExample:#include <vector>...vector<int> scores (100); //100 integer

scoresvector<Passenger>passengerList(20); //list of

20 passengers

Vector ContainerAllows direct access to the elements via an

index operatorIndices for the vector elements are in the

range from 0 to size() -1Example:

#include <vector>vector <int> v(20);

v[5]=15;

Vector OperationsSee http://cs.smu.ca/~porter/csc/ref/stl/cont_vector.htmlFor list of vector operations.

List ContainerStores elements by positionEach item in the list has both a value and a

memory address (pointer) that identifies the next item in the sequence

To access a specific data value in the list, one must start at the first position (front) and follow the pointers from element to element until data item is located.

List is not a direct access structureAdvantage: ability to add and remove items

efficiently at any position in the sequence

STL ListSee

http://cs.smu.ca/~porter/csc/ref/stl/cont_list.html

for list of STL list operations.

Stack ContainerAdapter ContainerThese containers restrict how elements

enter and leave a sequenceStack

allows access at only one end of the sequence (top)

Adds objects to container by pushing the object onto the stack

Removes objects from container by popping the stack

LIFO ordering (last end, first out)

Queue ContainerQueue

Allows access only at the front and rear of the sequence

Items enter at the rear and exit from the front

Example: waiting line at a grocery storeFIFO ordering (first-in first-out )push(add object to a queue)pop (remove object from queue)

Priority Queue ContainerPriority queue

Operations are similar to those of a stack or queue

Elements can enter the priority queue in any order

Once in the container, a delete operation removes the largest (or smallest) value

Example: a filtering system that takes in elements and then releases them in priority order 8

18 13 3 15

27

Set ContainerSet

Collection of unique values, called keys or set members

Contains operations that allow a programmer to:determine whether an item is a member of the set insert and delete items very efficiently5 1 3

6 27 15

Buick FordJeep BMW

Set A Set B

Multi-Set ContainerA multi-set is similar to a set, but the same

value can be in the set more than onceMulti-set container allows duplicates

Map ContainerImplements a key-value relationshipProgrammer can use a key to access

corresponding valuesExample: key could be a part number such

as A24-57 that corresponds to a part: 8.75 price and Martin manufacturerA22-56

A23-57A24-57

A24-57

8.75 Martin

A22-56 12.50 Calloway

A23-57 4.95 Mirage

Multi-map ContainerSimilar to a map container Multi-map container allows duplicates

How to access Components - IteratorIterator is an object that can access a

collection of like objects one object at a time.An iterator can traverse the collection of

objects.Each container class in STL has a

corresponding iterator that functions appropriately for the container

For example: an iterator in a vector class allows random access

An iterator in a list class would not allow random access (list requires sequential access)

Common Iterator Operations

* Return the item that the iterator currently references

++ Move the iterator to the next item in the list

-- Move the iterator to the previous item in the list

== Compare two iterators for equality!= Compare two iterators for inequality

STL List ClassConstructors and assignment

list <T> v;list<T> v(aList);l=aList;

Accessl.front() ----returns 1st element in the listl.back()----returns the last element in the list

STL ListInsert and Remove

l.push_front(value)l.push_back(value)

Iterator Delaration list<T>::iterator itr;

Iterator Optionsitr = l.begin() set iterator to beginning of the listItr = l.end() set iterator to after the end of the

list

Writing classes that work with the STL Classes that will be stored in STL containers should

explicitly define the following:◦ Default constructor◦ Copy constructor◦ Destructor◦ operator =◦ operator==◦ operator<

Not all of these are always necessary, but it might be easier to define them than to figure out which ones you actually need

Many STL programming errors can be traced to omitting or improperly defining these methods

More on STL ListsGo to: http://cs.smu.ca/~porter/csc/ref/stl/

Create a client file to read in 20 numbers into a list and print the list in reverse order.

Component DescriptionContainers Containers are used to manage collections of

objects of a certain kind. There are several different types of containers like deque, list, vector, map etc.

Algorithms Algorithms act on containers. They provide the means by which you will perform initialization, sorting, searching, and transforming of the contents of containers.

Iterators Iterators are used to step through the elements of collections of objects. These collections may be containers or subsets of containers.

#include <iostream> #include <vector> using namespace std; int main() { // create a vector to store int vector<int> vec; int i; // display the original size of vec cout << "vector size = " << vec.size() << endl; // push 5 values into the vector for(i = 0; i < 5; i++){ vec.push_back(i); } // display extended size of vec cout << "extended vector size = " << vec.size() << endl; // access 5 values from the vector for(i = 0; i < 5; i++){ cout << "value of vec [" << i << "] = " << vec[i] << endl; } // use iterator to access the values vector<int>::iterator v = vec.begin(); while( v != vec.end()) { cout << "value of v = " << *v << endl; v++; } return 0; }

vector size = 0 extended vector size = 5 value of vec [0] = 0 value of vec [1] = 1 value of vec [2] = 2 value of vec [3] = 3 value of vec [4] = 4 value of v = 0 value of v = 1 value of v = 2 value of v = 3 value of v = 4

The push_back( ) member function inserts value at the end of the vector, expanding its size as needed.The size( ) function displays the size of the vector.The function begin( ) returns an iterator to the start of the vector.The function end( ) returns an iterator to the end of the vector.

vector Array

list Doubly-linked list

slist Singly-linked list

queue FIFO (first-in, first-out) structure

dequeArray-like structure, with efficient insertion and removal at both ends

set Set of unique elements

stack LIFO (last in, first out) structure

push_frontInserts element before the first    (not available for vector)

pop_front Removes the first element    (not available for vector)

push_back Inserts element after the last

pop_back Removes the last element

The following member-functions are provided for most containers:

empty Boolean indicating if the container is empty

size Returns the number of elements

insert Inserts an element at a particular position

erase Removes an element at a particular position

clear Removes all the elements

resize Resizes the container

front Returns a reference to the first element

back Returns a reference to the last element

Also, most containers provide the following member-functions: