Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.

Slides:



Advertisements
Similar presentations
Data Structures Using C++ 2E
Advertisements

C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
More on the STL vector list stack queue priority_queue.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Standard Template Library (STL) Overview – Part 1 Yngvi Bjornsson.
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
Templates and the STL.
Writing Your Own STL Container Ray Lischner
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
ECE 250 Algorithms and Data Structures Douglas Wilhelm Harder, M.Math. LEL Department of Electrical and Computer Engineering University of Waterloo Waterloo,
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
Containers Overview and Class Vector
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
SNU OOPSLA Lab. Chap17. Standard Containers © copyright 2001 SNU OOPSLA Lab.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Data Structures Using C++ 2E Chapter 13 Standard Template Library (STL) II.
C++ STL CSCI 3110.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Templates code reuse - inheritance - template classes template classes - a class that is not data-type specific - eg. a class of Array of any type - intArray,
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
Lecture 7 : Intro. to STL (Standard Template Library)
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
A gentle introduction to the standard template library (STL) Some references:
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
STL – Standard Template Library L. Grewe. 2 Goals Lots of important algorithms, data structures in CS using Templates. is a software library partially.
The Standard Template Library Container Classes Version 1.0.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
C++ Review STL CONTAINERS.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Object-Oriented Programming (OOP) Lecture No. 42.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
Object-Oriented Programming (OOP) Lecture No. 41
CS212: Object Oriented Analysis and Design
Standard Template Library
Standard Template Library (STL)
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Basic Data Structures.
Chapter 22: Standard Template Library (STL)
CS212: Object Oriented Analysis and Design
Containers, Iterators, Algorithms, Thrust
Copyright © – Curt Hill STL List Details Copyright © – Curt Hill.
Lecture 8 : Intro. to STL (Standard Template Library)
Standard Template Library
Standard Template Library
A dictionary lookup mechanism
Standard Template Library
Presentation transcript:

Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient

Containers There are 3 types of containers –Sequence containers –Associative containers –Container adapters Sequence and Associative containers are first class containers There are 4 near containers –C-like arrays –String –Bitset –Valarray – high speed math

Container Classes Sequence Containers – just hold values. –vector – 1D array – rapid insertions and deletions at back – direct access to elements –deque – rapid insertions and deletions at front or back – direct access to any element –list – doubly linked list – rapid insertions and deletions anywhere

Associative Containers Associate values set – rapid lookup – no duplicates multiset – rapid lookup – duplicates allowed map – one to one mapping, no duplicates, rapid key lookup multimap – one to many mapping, duplicates allowed, rapid key based lookup

Container Adapters These implement data structures that can be implemented with different containers stack – last in first out – can be implemented with a vector, deque or a list. queue – first in first out priority_queue – highest priority is the first one out.

Member functions for all containers Default constructor – default initialization. There may be a variety of constructors for various initialization methods. Copy constructor – initializes a container to be a copy of the existing container. Destructor empty – returns true or false max_size – returns max size

More member functions size – returns the current size operator= - assigns one container to another operator< - returns true or false operator, >=, ==, != swap – swap the elements of 2 containers.

First class member functions These are only available to first class containers (sequence and associative) begin – return an iterator that refers to the first element of the container. end – return an iterator that refers to the position after the end of the container rbegin – return a reverse_iterator that refers to the last element of the container rend - return a reverse_iterator that refers to the position before the first element of the container erase – erases one or more elements clear – erases all elements from the container.

Using the STL Many implementations of the STL are different than normal libraries Some use the following method (using the vector class). #include using namespace std; Notice, no.h in the file name. Some implementations may work with the.h and no using.

The STL header files The header files are in –

Typedefs The following are typedefs defined in the first class containers. –value_type – the type of element stored in the container –reference – a reference to the type of element stored in the container –const_reference – reference that cannot change the contents of the container –pointer – a pointer to the type of element stored in the container –iterator – an iterator type to the element

More typedefs const_iterator – reverse_iterator – for going backwards in the container const_reverse_iterator difference_type – the type of the result of subtracting 2 iterators to the same container. size_type – the type used to count items in a container and index through a sequence container

Iterators Iterators are a lot like pointers. They tell where something is. An Iterator is implemented as a class This prevents many errors Allows as many iterators as you want for a class in both the implementation of the class and the using of the class

Iterator Categories Input – used to read an element from a container. Can only move forward. Can only go through the sequence once. Output – used to write an element to a container. Can only move forward. Only one pass. Forward – combines input and output and retain position in container Bi-directional – combines input and output and allows backward movement. Can have more than one pass. Random access – can jump to any element.

Iterators supported vector – random and above deque – random and above list – bi-directional and above set – bi-directional and above multiset – bi-directional and above map – bi-directional and above multimap – bi-directional and above stack – none queue – none priority_queue – none

Iterator Operations The following are for all iterator types –++p – preincrement –p++ - postincrement Input iterators –*p – dereference an iterator for an rvalue –p=p1 – assign iterators –p==p1 – compare for equality –p!=p1 – compare for inequality Output iterators –*p – dereference for use as lvalue –p=p1 – assign iterators

More iterator operators Forward operators –Same as input and output Bi-directional iterators –--p – predecrement –p-- - postdecrement Random-Access iterators –p+=i – increment p by i positions –p-=i – decrement p by i positions –p+i – p incremented by i positions –p-i –p[i] – return a reference to the element offset from p by i positions –p<p1 – true if p is before p1 –p>p1, p>=p1, p<=p1

Algorithms Algorithms are generic functions that work across all the containers. They are not member functions of a container class. This way the algorithms can be written without being rewritten for each class. Many algorithms work on a sequence by being sent a begin and end iterator.

Mutating sequence algorithms copy()transform()unique_copy()copy_backward() generate()unique()generate_n()swap_ranges() rotate()remove()remove_copy()remove_copy_if() replace()reverse()replace_copy_if()reverse_copy() fill()partition()rotate_copy()stable_partition() swap()iter_swap()replace_copy()remove_if() fill_n()replace_if()random_shuffle()

Non Mutating sequence alg. adjacent-find()count() count_if()equal() find()for_each() mismatch()search() search_n()

Numerical Algorithms Need to use header –accumulate() –inner_product() –partial_sum() –adjacent_difference()

Tips part 1 For any particular application, several different STL containers could be appropriate. Select the most appropriate container that achieves the best performance for that application. STL capabilities are implemented to operate efficiently across a wide variety of applications. You may need to write your own customized implementations for specialized applications.

Tips part 2 The STL approach allows general programs to be written so the code does not depend on the underlying container. STL avoids inheritance to achieve best run time performance. Know STL components. Choose the most appropriate container for your application. Attempting to dereference an iterator outside the container is an error. In particular, dereferencing end() will be an error.

Tips part 3 STL is extensible. It is straightforward to add new algorithms and to do so without changes to STL containers. STL algorithms can operate on STL containers and on pointer based C-like arrays. Since STL algorithms process many containers through iterators, one algorithm can often be used with many containers.

Tips, part 4 Applications that require frequent insertions and deletions at both ends of a container normally use a deque rather than a vector. Applications with frequent insertions and deletions in the middle of a container normally use a list. The vector container is best for random access. It is faster to insert many items at once than one at a time.

Sequence containers Vector and deque are based on arrays. List is a linked list data structure. Vector is a smart array. It can change size dynamically. When a vector needs more space, it reallocates an array of twice the size and copies the old contents into the new array. Can do vector assignment. Vector subscripting does not perform range checking. Use the member function at.

Sequence Container Operations The sequence containers also have the operations –push_back – insert at the end –pop_back – remove from the end

The vector Sequence Container Uses contiguous memory locations Supports random access iterators –Can use all the iterator functions All STL algorithms can operate on a vector.

Code with vector #include using namespace std; void main() { vector v; v.push_back(2); v.push_back(3); v.push_back(4); cout<<v.size()<<v.capacity()<<endl; vector ::const_iterator p1; for (p1=v.begin(); p1!=v.end(); p1++) cout << *p1; vector ::reverse_iterator p2; for (p2=v.rbegin(); p2 != v.rend(); p2++) cout<<*p2; }

Vector functions Copy Constructor –vector v(a, a+SIZE); –Creates v with a copy of a (which is a vector or c-type array) from beginning (a) to the end (a+SIZE, the one at a+SIZE is not copied). copy(a.begin(), a.end(), v.begin()); Remember, front and back cannot be used on an empty vector.

Addressing There are several ways to address an element of a vector. v[i]=value; v.at(i)=value; //subscript checking v.insert(v.begin()+i, value);// moves rest v.insert(pos, otherstart, otherend); v.erase(v.begin()+i); v.erase(begin, end); v.clear();//erases all If the element is a pointer, the erase does not delete the element.

List Operations myl.push_front(value); myl.pop_front(value); myl.splice(myl_pos, otherlist); –Remove elements in otherlist and put before myl_pos in myl myl.splice(myl_pos, otherlist, other_pos); // move 1 element myl.splice(myl_pos, otherlist, other_start, other_end);

More List Operations myl.remove(myl_pos); myl.sort(); myl.sort(bool cmp(type, type)); –Sort using a comparison function (needed for list of records). myl.unique(); –Remove duplicates in a sorted list. –Need bool function for equality if not using the default. myl.merge(other); –Takes 2 sorted lists and merges them –Can add a bool function for merge condition.

Last of List operations myl.reverse(); myl.swap(other); –Swaps the entire container myl.assign(other_start, other_end); –Make myl contain only part of other.

Deque Operations Has basically the same functions as vector Additionally there are –push_front –pop_front

Associative classes These containers are key oriented Set and multiset just have a key; set is for unique values, and multiset allows duplicate values. Map and multimap have a record associated with each key. All associative containers can –find –lower_bound –upper_bound –count

Multiset There are built in comparison templated functions less and greater Need to have defined on the type. Kept in order The order is determined by a comparator function object given during creation. Supports bidirectional iterators Uses a somewhat balanced tree to implement

Operations Must use the include file –Contains both the set and multiset classes Constructor multiset > –cmp is less or greater insert(value) int count(value) – how many of value are in the multiset (not used in set). iterator find(value) – gives an iterator to the value if found – returns end() if not found.

More Methods void insert(arraystart, arrayend) – adds many values to the multiset. The pair class –pair pobj; –This is a class to hold 2 values. –Data is public –pobj.first and pobj.second pair equal_range(value) – returns an iterator pair pointing to the beginning and end of the range containing the single value pair ::iterator, multiset ::iterator> p; p=myset.equal_range(37);

Set No duplicates The insert function returns an iterator, bool pair. If the insert worked (not a duplicate), the bool is true and the iterator points to where it was inserted. If the insert failed (tried to insert a duplicate), bool is false and the iterator value is unimportant.

Multimap Use the header for both map and multimap. Methods: –multimap mobj; –int count(keyvalue) –void insert(pair) –multimap ::value_type(v 1, v 2 ) Creates a pair with v 1 and v 2 –iterators point to a pair itr->first itr->second

Map Same functions and idea as multimap, just no duplicates. Can use mobj[key] This is not a subscript It returns a reference to a position (who knows where) associated with that key. You can place values there or use the values from there.

Stack Adapter Implemented with a vector, list or deque (default). void push(value) void pop() type top() bool empty() int size() stack >stk; stack stk;

Queue Adaptor Implemented with a list or a deque (default). push – add to back pop – remove from front front – get first value back – get last value empty – size

Priority Queue Implemented with a deque or vector (default). Uses a heap principle push pop top empty Size

Algorithms fill(iter_start, iter_end, value) –Fill the container from start to end with value. fill_n(iter_start, count, value) –Fill the container with count copies of value starting at start. generate(start, end, function) –Function returns value of type, takes no arg. Places return value in container. Called several times. generate_n(start, count, function)

More Algorithms bool equal(start 1, end 1, start 2 ) –Returns true if all values between start and end of container 1 are the same as the corresponding values in container 2. bool equal(start 1, end 1, start 2, func) –Func is an equality boolean function that takes 2 args of type. pair mismatch(s 1, e 1,s 2 ) –Returns a pair of iterators for the first case of a value in container 1 not equal to the corresponding value in container 2. pair<> mismatch(s 1, e 1,s 2, func)

Algorithms again bool lexicographical_compare(s 1,e 1,s 2, e 2 ) –Used mainly with strings. Returns true if the first container is less than second lexicographically. remove(s,e,value) –Remove all occurances of value between s and e. remove_copy( s 1,e 1,s 2,value) –s 2 has a copy of s 1 with instances of value removed remove_if( s,e,bool_func) –Removes the value when bool_func is true Remove_copy_if( s 1,e 1,s 2, bool_func)

Even More replace(s,e,old_value,new_value) replace_if(s,e, bool_func, new) –Replaces value with new if old passed to bool_func returns true. replace_copy( s 1,e 1,s 2, old,new) –Makes a copy of the container with instances of old value replaced with new value. replace_copy_if( s 1,e 1,s 2, bool_func,new)

Math type functions random_shuffle(begin, end) –Change the order of items between begin and end. count(begin, end, value) –Give a count of items with value count_if(begin, end, bool_func) min_element(begin, end) max_element(begin, end) –Min and max return iterators.

More math accumulate(s,e,start_value) –Adds up values accumulate(s,e,start_value,func) –func tells how to accumulate (can multiply, etc.). func takes 2 args, the partial result and the new value. for_each(s,e,func) –Passes values between s and e to func transform( s 1,e 1,s 2, func) –Passes each value from s to e to func and places the result in container 2.

Searching find(s,e,value) –Returns an iterator to the element with value. find_if(s,e,bool_func) –Returns an iterator to an element that makes bool_func true. sort(s,e) bool binary_search(s,e,value)

Swapping swap(ref, ref) –Takes 2 references and swaps the values iter_swap(iter, iter) –Takes 2 iterators and swaps the values swap_ranges(start 1, end 1, start 2 ) –Swap the elements from start 1 to end 1 with the same number of elements starting at start 2

More algorithms copy_backward(start 1, end 1, end 2 ) –Copies from start 1 up to end 1 placing the values starting at end 2 and working backward. Returns iterator positioned at the beginning of the resulting list. merge(s 1,e 1,s 2,e 2,rstart) –Merge the sorted values from s 1 to e 1 with the sorted values from s 2 to e 2 into the container starting at rstart. Can also have a cmp function for order

Other Algorithms unique(start, end) –Removes duplicates unique_copy(s 1,e 1,s 2 ) reverse(start,end) –Reverses all the elements reverse_copy(s 1,e 1,s 2 ) inplace_merge(s 1,s 2,e 2 ) –Merges 2 sorted sequences from the same container back into the same container. Merges from s 1 to s 2 with from s 2 to e 2.

Set Operations Values must be ordered in container bool includes(s 1,e 1,s 2,e 2 ) –Returns true if the set from s 2 to e 2 is contained in the set from s 1 to e 1 set_difference(s 1,e 1,s 2,e 2,r 1 ) –Places all the values that are in container 1 but not in container 2 into container r. set_intersection(s 1,e 1,s 2,e 2,r 1 ) –Places values that are in both container 1 and container 2 into container r.

Last of set operations set_symmetric_difference(s 1,e 1,s 2,e 2,r 1 ) –Place values that are in container 1 but not in container 2 into container r and place values that are in container 2 but not in container 1 into container r. set_union(s 1,e 1,s 2,e 2,r 1 ) –Place the union of containers 1 and 2 into container r.

Ranges lower_bound(s,e, value) –Returns an iterator that gives the first position where value could be inserted in sorted order. upper_bound(s,e,value) –Returns an iterator that gives the last position where a value could be inserted in sorted order. equal_range(s,e,value) –Returns a pair of iterators that are the same as calling lower and upper bound

Heapsort make_heap(s,e) –Makes a heap in the container sort_heap(s,e) –Sort values that are already in a heap push_heap(s,e) –Used after a push_back function call. Makes a heap out of what was a heap with one item added.

Last ones min(value 1, value 2 ) max(value 1,value 2 )