. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.

Slides:



Advertisements
Similar presentations
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Advertisements

. 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,
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
What is generic programming? The essence of the generic programming approach is concept development: systematic classification of computing components.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
More on the STL vector list stack queue priority_queue.
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)
Standard Template Library (STL) Overview – Part 1 Yngvi Bjornsson.
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
Generic programming starts with algorithms. Lift Minimal requirements: works with maximal family of types Concrete algorithm: requires specific data type.
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
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.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
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.
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.
Standard Template Library Programming paradigm: generic programming the decomposition of programs into components which may be developed separately and.
Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
Containers Overview and Class Vector
Containers and Iterators CNS 3370 Copyright 2003, Fresh Sources, Inc.
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.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
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)
The C++ Standard Template Library. What is STL A subset of the standard C++ library –The string class is not part of it! 3 major components –Algorithms.
C++ STL CSCI 3110.
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan and A. Ranade.
Templates Mark Hennessy Dept Computer Scicene NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
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.
Introduction to the Standard Template Library (STL) A container class holds a number of similar objects. Examples: –Vector –List –Stack –Queue –Set –Map.
1 Iterators Good reference site:
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.
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.
CS 403: Programming Languages Lecture 24 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
Intro to the C++ STL Timmie Smith September 6, 2001.
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
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.
More STL Container Classes ECE Last Time Templates –Functions –Classes template void swap_val (VariableType &a, VariableType &b) { VariableType.
1 The Standard Template Library Drozdek Section 3.7.
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Introduction to Templates and Standard Template Library 1.
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.
Standard Template Library (STL)
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Programming with Concepts
Chapter 22: Standard Template Library (STL)
priority_queue<T>
STL Библиотека стандартных шаблонов
Standard Template Library
Standard Template Library
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: C++ Standard Library

Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations of algorithm-container u Simple & uniform interface: interface through templates (not inheritence) u Efficiency u Reference:

Components u Containers: data structures vector, list, map, set, deque u Adaptors: high-level data structure stack, queue, priority_queue u Iterators: allow access into containers u Algorithms: base algorithms sort, copy, search, min, max, … u Streams: input/output u String

Quick Facts Vector  Implements an array of objects of type T  Allows random-access to array  Can grow on as needed basis Map  “Associative Array”: maps keys to values  Implemented as balanced binary tree

Example I – ShapeManager revisited #include using namespace std; class Shape { public: virtual void draw() = 0; virtual ~Shape() {}; }; class Circle : public Shape { public: void draw() { cout << "Circle::draw\n"; } ~Circle() { cout << "~Circle\n"; } }; class Triangle : public Shape { public: void draw() { cout << "Triangle::draw\n"; } ~Triangle() { cout << "~Triangle\n"; } }; class Square : public Shape { public: void draw() { cout << "Square::draw\n"; } ~Square() { cout << "~Square\n"; } };

typedef std::vector Container; typedef Container::iterator Iter; int main() { Container shapes; shapes.push_back(new Circle); shapes.push_back(new Square); shapes.push_back(new Triangle); for(int k = 0;k < shapes.size();k++ ) shapes[i]->draw(); //use operator[] for(Iter j = shapes.begin(); j != shapes.end(); j++) delete *j; //use iterator and dereferencing } ///:~ Example I – ShapeManager revisited

Example II – unique word counter #include using namespace std; int main(int argc, char* argv[]) { ifstream source(argv[1]); string word; set words; while(source >> word) words.insert(word); copy(words.begin(), words.end(), ostream_iterator (cout, "\n")); cout << "Number of unique words:" << words.size() << endl; } ///:~

Containers u Holds copies of elements u Assumes Copy Ctor & operator = u The standard defines the interface, not the implementation u Two main classes  Sequential containers: list, vector,....  Associative containers: map, multimap, set...

Sequential Containers u Maintain a linear sequence of objects Types of operations u Access/insertion/deletion of elements at the front/end of sequence u Random access to elements

Sequential Containers list - a linked list of objects  Efficient insertion/deletion in front/end/middle vector - an extendable sequence of objects  Efficient insertion/deletion at end  Random access deque – double-ended queue  Efficient insertion/deletion at front/end  Random access

Sequential Container Interface u size(), empty() u push_front(x), push_back(x) u front(), back() u pop_front(), pop_back() vector & deque u operator[](int index)

Associative Containers u Maintain a collection of keys u Requires order on keys (less-than operator) u Keys can be accessed based on their order (Typical) Implementation: u red-black binary trees u O(log n) time for access/insert/delete

Associative Containers Set u A set of unique keys Map u Associate a value to key (associative array) u Unique value of each key Multiset Multimap u Same, but allow multiple values

Example #include using namespace std; typedef map WordMap; typedef WordMap::iterator WMIter; int main(int argc, char* argv[]) { ifstream in(argv[1]); WordMap wordmap; string word; while(in >> word) wordmap[word]++; for(WMIter w = wordmap.begin(); w != wordmap.end(); w++) cout << (*w).first << ": " << (*w).second.val() << endl; } ///:~ class Count { int i; public: Count() : i(0) {} void operator++(int) { i++; } int& val() { return i; } };

Associative Containers & Order u Associative containers use operator< as default order u We can control order by using our own comparison function u To understand this issue, we need to use function object

Function Objects A class that implements operator() Advantages: u Use the template mechanism (class versus function) u Enable accumulating information in the function object

Example template class less { public: bool operator()(T& lhs, T& rhs) { return lhs < rhs; } }; less cmp; // declare an object if( cmp(1,2) ) … if( less ()(1,2) ) … Creates temporary objects, and then call operator()

Function Object Bases u Base classes for the functions objects are defined in STL. u These provide standard names for the arguments and return types. template class less : public binary_function { … }

Function Object Bases template struct unary_function { typedef Arg argument_type; typedef Res return_type; }; template struct binary_function { typedef Arg first_argument_type; typedef Arg2 second_argument_type; typedef Res return_type; };

Using Comparators template > class set { … } … set s1; set > s2;// same type set s3; MyComp cmp; set s4(cmp); Creates a new MyComp object. Use given MyComp object.

STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator++, and operator— u Different types of iterators - to support read, write and random access u Containers define their own iterator types u Changing the container can invalidate the iterator

Iterator Types u Output: write only and can write only once u Input: read many times each item u Forward supports both read and write u Bi-directional support also decrement u Random supports random access (just like C pointer)

Iterators & Containers Bidirectional iterators: u list, map, set Random access iterators: u vector, deque Input/output/forward iterators: u iostreams

Iterators and Containers T::iterator – iterator type for type T begin() – front of the container end() – element after last Container C … Container::iterator i for( i = C.begin(); i != C.end(); i++) // do something with *i

Iterators & Streams Can access iostreams through iterators: istream_iterator in(cin); istream_iterator endOfInput; ostream_iterator out(cout); while( in != endOfInput ) { string s = *in++; *out++ = s; *out++ = “ “; } see useStreamIterators.cpp

Sequence Adapters u Adapters of basic containers u Very easy, but limited interface stack  provides push, pop, top, size and empty queue  also provides back priority_queue u provides same interface as stack u uses a compare function object

Algorithms Overview u Sequence operations  Non modifying: for_each, find, count, search, mismatch, equal  Modifying: transform, copy, swap, replace, fill, generate, remove, unique, reverse, rotate, random_shuffle u Sorted sequences operations  sort, lower_bound, upper_bound, equal_range, binary_search, merge, includes, set_union, intersection, difference, symmetric_difference

Algorithms u Most STL algorithms works on sequences u Sequences are passed as two iterators:  beginning element  element one after last u Algorithms depend on iterator type not on container type pq sequence [p,q)

Copy template Out copy(In first, In last, Out res) { while (first != last) *res++ = *first++; return res; } See useCopy.cpp

Non-modifying Sequence Algorithms  In find(In first, In last, const T& val) find the first occurence of val in the sequence  In find_if(In first, In last, Pred p) find the first element satisfying p  I1 find_first_of(I1 f1, I1 l1, I2 f2, I2 l2) find the first match between two sequences.  I1 search( I1 f1, I1 l1, I2 f1, I2 l2 ) search for the sequence f2...l2 inside f1..l1

Sorted Sequence Algorithms  sort(In first, In last[, class cmp]) find the first occurence of val in the sequence  In lower_bound(In first, In last, T const & val[, class cmp]) find the first element not less than val  bool binary_search(In first, In last, T const & val[, class cmp]) check if val appears in the sequence  Out merge( I1 f1, I1 l1, I2 f1, I2 l2, Out out ) merge two sorted sequences and write the merged sequence onto the output iterator out