Introduction to the STL

Slides:



Advertisements
Similar presentations
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Advertisements

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
. 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.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
Standard Containers: Vectors
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
More on the STL vector list stack queue priority_queue.
OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
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.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
Standard Template Library C++ introduced both object-oriented ideas, as well as templates to C Templates are ways to write general code around objects.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
CSE 332: Combining STL features Combining STL Features STL has containers, iterators, algorithms, and functors –With several to many different varieties.
Writing Your Own STL Container Ray Lischner
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
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:
DATA STRUCTURES ACM EXECUTIVE BODY 2k11.  A series of elements of same type  Placed in contiguous memory locations  Can be individually referenced.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
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.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Generic Programming Using the C++ Standard Template Library.
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.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan and A. Ranade.
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.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
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.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
 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 11 Standard Template Library Lists Iterators Sets Maps.
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.
The Standard Template Library Container Classes Version 1.0.
Strings Jarret Raim C Strings Same as arrays of characters. Use pointers. Require static declarations (compile time). No bounds checking. No easy.
C++ Review STL CONTAINERS.
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 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
Vectors the better arrays. Why Vectors l vectors are implemented as a class (a template to be exact) l they serve the same purpose as arrays but using.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
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.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
Object-Oriented Programming (OOP) Lecture No. 41
Introduction to olympic programming
Standard Template Library (STL)
Collections Intro What is the STL? Templates, collections, & iterators
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
STL (Standard Template Library)
Standard Template Library
C++ Programming: chapter 10 – STL
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
Chapter 3 Lists, Stacks, and Queues
Presentation transcript:

Introduction to the STL Eric Tune

What is STL STL = Standard Template Library Part of the ISO Standard C++ Library Data Structures and algorithms for C++.

Why should I use STL? Reduce development time. Code readability Data-structures already written and debugged. Code readability Fit more meaningful stuff on one page. Robustness STL data structures grow automatically. Portable code. Maintainable code Easy

Keywords you DONT need class virtual public private template mutable

Example Program #include <map> #include <string> map<string,float> price; price[“snapple”] = 0.75; price[“coke”] = 0.50; string item; double total=0; while ( cin >> item ) total += price[item];

Example Program #include <map> #include <string> map<string,float> price; price[“snapple”] = 0.75; price[“coke”] = 0.50; string item; double total=0; while ( cin >> item ) total += price[item];

Example Program #include <map> #include <string> map<string,float> price; price[“snapple”] = 0.75; price[“coke”] = 0.50; string item; double total=0; while ( cin >> item ) total += price[item];

Example Program #include <map> #include <string> map<string,float> price; price[“snapple”] = 0.75; price[“coke”] = 0.50; string item; double total=0; while ( cin >> item ) total += price[item];

The ‘Top 3’ data structures map Any key type, any value type. Sorted. vector Like c array, but auto-extending. list doubly-linked list

Simple Example of Map map<long,int> root; root[4] = 2; long l; cin >> l; if (root.count(l)) cout<<root[l] else cout<<“Not perfect square”;

Two ways to use Vector Preallocate Grow tail vector<int> v(100); v[80]=1; // okay v[200]=1; // bad Grow tail vector<int> v2; int i; while (cin >> i) v.push_back(i);

Example of List list<int> L; for(int i=1; i<=5; ++i) L.push_back(i); //delete second item. L.erase( ++L.begin() ); copy( L.begin(). L.end(), ostream_iterator<int>(cout, “,")); // Prints: 1,2,3,5

The three parts of STL Containers Algorithms Iterators

Iterators Declaring Front of container Past the end list<int>::iterator li; Front of container list<int> L; li = L.begin(); Past the end li = L.end();

Iterators Can increment Can be dereferenced list<int>::iterator li; list<int> L; li=L.begin(); ++li; // Second thing; Can be dereferenced *li = 10;

Algorithms Take iterators as arguments list<int> L; vector<int> V; // put list in vector copy( L.begin(), L.end(), V.begin() );

List Example Again list<int> L; for(int i=1; i<=5; ++i) L.push_back(i); //delete second item. L.erase( ++L.begin() ); copy( L.begin(). L.end(), ostream_iterator<int>(cout, “,")); // Prints: 1,2,3,5

Typdefs Annoying to type long names Simplify with typedef map<Name, list<PhoneNum> > phonebook; map<Name, list<PhoneNum> >::iterator finger; Simplify with typedef typedef PB map<Name,list<PhoneNum> >; PB phonebook; PB::iterator finger; Easy to change implementation.

Using your own classes in STL Containers Might need: Assignment Operator, operator=() Default Constructor For sorted types, like map<> Need less-than operator: operator<() Some types have this by default: int, char, string Some do not: char *

Example of User-Defined Type struct point { float x; float y; } vector<point> points; point p; p.x=1; p.y=1; points.push_back(1);

Example of User-Defined Type Sorted container needs sort function. struct full_name { char * first; char * last; bool operator<(full_name & a) {return strcmp(first, a.first) < 0;} } map<full_name,int> phonebook;

What do I need? g++ 2.96 Mostly works with MSVC++ Fine for all examples in this talk 3.0.x is even better using namespace std; Mostly works with MSVC++ So i am told.

Performance Personal experience 1: STL implementation was 40% slower than hand-optimized version. STL: used deque Hand Coded: Used “circular buffer” array; Spent several days debugging the hand-coded version. In my case, not worth it. Still have prototype: way to debug fast version.

Performance Personal experience 2 Application with STL list ~5% slower than custom list. Custom list “intrusive” struct foo { int a; foo * next; }; Can only put foo in one list at a time 

Pitfalls Accessing an invalid vector<> element. Solutions: vector<int> v; v[100]=1; // Whoops! Solutions: use push_back() Preallocate with constructor. Reallocate with reserve() Check capacity()

Pitfalls Inadvertently inserting into map<>. if (foo[”bob”]==1) //silently created entry “bob” Use count() to check for a key without creating a new entry. if ( foo.count(“bob”) )

Pitfalls Not using empty() on list<> . Slow Fast if ( my_list.count() == 0 ) { ... } Fast if ( my_list.empty() ) {...}

Pitfalls Using invalid iterator Use return value of erase to advance list<int> L; list<int>::iterator li; li = L.begin(); L.erase(li); ++li; // WRONG Use return value of erase to advance li = L.erase(li); // RIGHT

Common Compiler Errors vector<vector<int>> vv; missing space lexer thinks it is a right-shift. any error message with pair<...> map<a,b> implemented with pair<a,b>

STL versus Java Containters Holds any type No virtual function calls Static type-checking Java Containers Holds things derived from Object Virtual Function Call overhead No Static type-checking

Other data structures set, multiset, multimap queue, priority_queue stack , deque slist, bitset, valarray

Generic Programming Resources STL Reference Pages www.sgi.com/tech/stl/

More Generic Programming GTL : Graph Template Library BGL : Boost Graph Library MTL : Matrix Template Library ITL : Iterative Template Library