STL – Standard Template Library

Slides:



Advertisements
Similar presentations
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Advertisements

Data Structures Using C++ 2E
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
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,
What is generic programming? The essence of the generic programming approach is concept development: systematic classification of computing components.
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
Concept= a set of abstractions (e.g., types) (Generic Programming) Programming with Concepts defined by a set of requirements {vector, deque, list, set,
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
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.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Templates and the STL.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Writing Your Own STL Container Ray Lischner
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
Data Structures Using C++ 2E
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
Generic Programming Using the C++ Standard Template Library.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
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,
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
Intro to the C++ STL Timmie Smith September 6, 2001.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
Lecture 36 OOP The STL Standard Template Library
Motivation for Generic Programming in C++
CS212: Object Oriented Analysis and Design
Regarding homework 9 Many low grades
C++ Templates.
Lecture 7-2 : STL Iterators
Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library (STL)
Generic Programming Techniques in C++
Starting Out with C++ Early Objects Eighth Edition
The C++ Algorithm Libraries
Collections Intro What is the STL? Templates, collections, & iterators
What remains Topics Assignments Final exam
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Programming with Concepts
Lecture 7-2 : STL Iterators
CS212: Object Oriented Analysis and Design
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Generic Programming Karl Lieberherr 12/1/2018 Generic Programming.
priority_queue<T>
Containers, Iterators, Algorithms, Thrust
Elements are always copied when they are put into a container
Standard Version of Starting Out with C++, 4th Edition
Iterators and STL Containers
Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library (STL)
Lecture 8-2 : STL Iterators and Algorithms
C++ Templates L03 - Iterator 10 – Iterator.
Lab4 problems More about templates Some STL
Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
An Introduction to STL.
Chapter 3 Lists, Stacks, and Queues
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Standard Template Library
Presentation transcript:

STL – Standard Template Library Guaranteed to be available on all compilers implement the Standard Template library All components are templates, can be used for arbitrary element types.

STL Entities Entities: Container classes Sequence containers Associative ordered containers Iterators Generic algorithms Function objects (functors) Other (not covered here) Allocators Adaptors

Old Structure Queue Stack algorithm List algorithm hash algorithm

New Structure with STL Algorithm Iterator Container Queue List Stack hash Container Algorithm Iterator The iterator is a bridge between Container and Algorithm

Concepts A concept is a set of abstractions Defined by a set of requirements Example: a container concept {vector<T>, list<T>, set<K>, map<K,T>, … } generic algorithms : algorithms that work correctly and efficiently for every abstraction in a concept Definition: Container refines Basic-container; uses Input-iterator; introduces begin(containers) -> iterators, end(containers) -> iterators, size(containers) -> naturals, empty(containers) -> bool; requires (for c: containers) size(c) = size(range(c, begin(c), end(c))), empty(c) = (size(c) = 0), valid(range(c, begin(c), end(c))).

Container A template, parameterized on element type Represents a group of homogeneous objects Two main types: Sequence containers : vector, deque, list Associative containers: set, multiset, map, Multimap All containers support: bool empty() const; iterator begin() const; iterator end() const; int size() const; Containers are characterized by complexity metrics # of operations for insertion, deletion # of operations for lookup

Iterator Points to one node in a list Advances to next node Compares with other iterators Special value denotes “one past end” Make heavily use of operator overloading. Iterator hierarchy

Iterator Example #include <list> // list class library using namespace std; void squareList(list<int>& nums) { list<int>::iterator it; for(it=nums.begin(); it != nums.end(); it++) *it = *it * *it; // Modify each element. }

Sequence Containers vector<T> deque<T> list<T>: Random access, variable size, constant insertion time. Description: http://www.sgi.com/tech/stl/Vector.html deque<T> Random access, variable size Description: http://www.sgi.com/tech/stl/Deque.html list<T>: Bidirectional access, access time O(n), constant insertion time Description: http://www.sgi.com/tech/stl/List.html

Simple Example - list #include <iostream> #include <list> using namespace std; int main(){ list<int> myContainer; list<int>::iterator it; myContainer.push_front(10); myContainer.push_front(20); myContainer.push_back(30); myContainer.push_back(40); for(it=myContainer.begin(); it!=myContainer.end(); it++) cout << *it << endl; myContainer.remove(30); // requires operator== myContainer.find(20); return 0; {

Associative containers Containers based on keys set<key> keys and data are the same, unique keys Description: http://www.sgi.com/tech/stl/set.html multiset<key> keys and data are the same, non-unique keys Description: http://www.sgi.com/tech/stl/multiset.html map<key,T> keys and data are paired, unique keys Description: http://www.sgi.com/tech/stl/Map.html multimap<key,T>: keys and data are pared, non-unique keys Description: http://www.sgi.com/tech/stl/Multimap.html

Example - Map We will define a map of class Person class Person { string m_sName; int m_iAge; public: typedef unsigned key; Person (const string sName, const int iAge): m_sName (sName), m_iAge (iAge) {}; Person () : m_iAge (0) {}; Person (const Person & p): m_sName (p.m_sName), m_iAge (p.m_iAge) {}; Person & operator= (const Person & rhs) {…} GetName () const { return m_sName; }; int GetAge () const { return m_iAge; }; };

Map class People } public: map<Person::key, Person> m_mapPerson; typedef pair<Person::key,Person> PersonPair; friend ostream& operator<<(ostream & s, const People & o){ map<Person::key,Person>::const_iterator it; for(it=o.m_mapPerson.begin();it!=o.m_mapPerson.end(); it++) s << (*it).first << ":" << (*it).second << endl; return s; void insert(Person::key k, Person p){ m_mapPerson[k] = p; };

functors Motivation: Sometimes it is useful to pass functions as parameters Usually results in messy/confusing code Functions can’t hold a meaningful state STL’s solution: function objects (functors) bool lessAbsoluteValue(float a, float b) { return abs(a) < abs(b); } bool (*mycomparison)(float, float); mycomparison = &lessAbsoluteValue; void sort(bool(*cmpfunc)(float, float), std::vector<float>);

functors Classes that implements the function call operator (operator()) Use example: sort(x.begin(), x.end(), lessAbsoluteValue()); class lessAbsoluteValue { public: bool operator()(float a, float b) const { return abs(a) < abs(b); } };

Applying functors to a range struct add { add( int n) : m_n( n) {} void operator()( int & value) { value += m_n; } private: int m_n; }; int main() { int a[] = { 335, 33, 98, 39, 54, 24, 3 }; int nElements = sizeof(a) / sizeof(a[ 0]); std::for_each( a, a + nElements, add( 10)); }

functor adaptors wrapper functors that call member functions mem_fun: works on member functions through a pointer mem_fun_ref: works on member functions through an object or a reference ptr_fun: works on global functions through a function pointer vector<SceneNode*> nodes; … sort(nodes.begin(), nodes.end(), mem_fun(&SceneNode::renderFirst));

Algorithms STL defines many different algorithms Templated function of common operations on containers Four categories of algorithms: Non-mutating algorithms Mutating algorithms Sorting algorithms Generalized numerical algorithms

Non-mutating algorithms find – looks for a specific item in a sequence for_each – applies a functor to a range of elements in a sequence list<string> players; … if (find(players.begin(), players.end(), wantedName) != players.end()) { …} template<class T> struct print { print(ostream& out) : os(out), count(0) {} void operator() (T x) { os << x << ' '; ++count; } ostream& os; int count; }; … int A[] = {1, 4, 2, 8, 5, 7}; const int N = sizeof(A) / sizeof(int); print<int> P = for_each(A, A + N, print<int>(cout));

Mutating Algorithms copy - Copies all elements in a specified range to another range reverse(first, last) – Reverse the elements in the sequence rotate(first, middle, last) – Shifts elements until middle element is at the first position random_shuffle - Shuffles all elements in the range // Copy the first 10 scores to the highscore table list<int> highcores; copy(scores.begin(), scores.begin()+10, highscores.begin());

Sorting algorithms sort Sorts all the elements in a range (based on quicksort) Uses operator< or a functor passed as an argument class Player { public: bool operator<(const Player& p) { return this->score_ < p.score_; } … vector<Player> players; sort(players.begin(), players.end());

Generalized numerical algorithms accumulate(first, last, init) Sums of all elements in a range, starting with initial value partial_sum(first, last, output) Sequence of numbers created by adding all the elements up to the nth element for each of the output elements adjacent_difference(first, last, output) Sequence of differences between adjacent pairs inner_product Calculates dot product for two different ranges

Algorithm+Container+Functor #include <cstring> #include <algorithm> #include <iostream> using namespace std; class CStringCompare { public: bool operator()(const char* s1, const char* s2) { return strcmp(s1, s2) < 0; } }; int main() { vector<string> cartoons; cartoons. push_back(“Mickey”); cartoons. push_back(“Minnie”); cartoons. push_back(“Goofy”); sort(cartoons.begin(), cartoons.end(), StringCompare()); for (int i = 0; i < numberOfArgs; ++i) cout << args[i] << endl; return 0; } Output: Goofey Mickey Minnie