An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.

Slides:



Advertisements
Similar presentations
Hold data and provide access to it. Random-access containers: -Allow accessing any element by index -arrays, vectors Sequential containers: -Allow accessing.
Advertisements

SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Beginning C++ Through Game Programming, Second Edition
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
C++ fundamentals.
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.
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.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
Object Oriented Programming Elhanan Borenstein Lecture #11 copyrights © Elhanan Borenstein.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
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.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
Generic Programming Using the C++ Standard Template Library.
1 C++ Syntax and Semantics, and the Program Development Process.
Pointers OVERVIEW.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
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.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
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.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
 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.
Templates “Generic Programming” ECE Templates A way to write code once that works for many different types of variables –float, int, char, string,
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.
Lecture 7 : Intro. to STL (Standard Template Library)
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Starting Out with C++, 3 rd Edition Introduction to the STL vector The Standard Template Library (or STL) is a collection of data types and algorithms.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Data Structures and Algorithm Analysis Dr. Ken Cosh Linked Lists.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
Standard Template Library
CS212: Object Oriented Analysis and Design
“Generic Programming” ECE 297
Programming with ANSI C ++
Vectors Holds a set of elements, like an array
C++ Standard Library.
Standard Template Library (STL)
Chapter 16 Linked Structures
Engineering Problem Solving with C++, Etter
Standard Template Library
Today’s Objectives 28-Jun-2006 Announcements
Standard Template Library
Standard C++ Library Part II.
An Introduction to STL.
Presentation transcript:

An Introduction to STL

The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a library of class and function templates which has come to be known as the STL.  In 1994, STL was adopted as part of ANSI/ISO Standard C++.

The C++ Standard Template Libraries  STL had three basic components: ContainersContainers Generic class templates for storing collection of data. AlgorithmsAlgorithms Generic function templates for operating on containers. IteratorsIterators Generalized ‘smart’ pointers that facilitate use of containers. They provide an interface that is needed for STL algorithms to operate on STL containers.  String abstraction was added during standardization.

Why use STL?  STL offers an assortment of containers  STL publicizes the time and storage complexity of its containers  STL containers grow and shrink in size automatically  STL provides built-in algorithms for processing containers  STL provides iterators that make the containers and algorithms flexible and efficient.  STL is extensible which means that users can add new containers and new algorithms such that: STL algorithms can process STL containers as well as user defined containersSTL algorithms can process STL containers as well as user defined containers User defined algorithms can process STL containers as well user defined containersUser defined algorithms can process STL containers as well user defined containers

Strings  In C we used char * to represent a string.  The C++ standard library provides a common implementation of a string class abstraction named string.

Hello World - C #include void main() { // create string ‘str’ = “Hello world!” char *str = “Hello World!”; printf(“%s\n”, str); }

Hello World – C++ #include #include using namespace std; int main() { // create string ‘str’ = “Hello world!” string str = “Hello World!”; cout << str << endl; return 0; }

String  To use the string type simply include its header file. #include  To use the string type simply include its header file. #include

Creating strings string str = “some text”; or string str(“some text”); other ways: string s1(7,‘a’); string s2 = s1;

string length The length of string is returned by its size() operation. #include string str = “something”; cout string str = “something”; cout << “The size of “ << str << “is “ << str.size() << “characters.” << endl;

The size method str.size() ??? In C we had structs containing only data, In C++, we have : class string { … public: public:… unsigned int size(); …};

String concatenation concatenating one string to another is done by the ‘+’ operator. string str1 = “Here ”; string str2 = “comes the sun”; string concat_str = str1 + str2;

String comparison To check if two strings are equal use the ‘==‘ operator. string str1 = “Here ”; string str2 = “comes the sun”; if ( str1 == str2 ) /* do something */ else /* do something else */

String assignment To assign one string to another use the “=“ operator. string str1 = “Sgt. Pappers”; string str2 = “lonely hearts club bend”; str2 = str1; Now : str2 equals “ Sgt. Pappers ”

What more ?  Containers  Algorithms

Containers Data structures that hold anything (other objects).  list: doubly linked list.  vector: similar to a C array, but dynamic.  map: set of ordered key/value pairs.  Set: set of ordered keys.

Algorithms generic functions that handle common tasks such as searching, sorting, comparing, and editing:  find  merge  reverse  sort  and more: count, random shuffle, remove, Nth-element, rotate.

Vector  Provides an alternative to the built in array.  A vector is self grown.  Use It instead of the built in array!

Defining a new vector Syntax : vector Syntax : vector For example : vector - vector of integers. vector - vector of strings. vector - vector of pointers to integers. vector - vector of Shape objects. Shape is a user defined class.

Using Vector  #include  #include  Two ways to use the vector type: 1.Array style. 2.STL style

Using a Vector – Array Style We mimic the use of built-in array. void simple_example() { const int N = 10; vector ivec(N); for (int i=0; i < 10; ++i) cin >> ivec[i]; int ia[N]; for ( int j = 0; j < N; ++j) ia[j] = ivec[j]; }

Using a vector – STL style We define an empty vector vector svec; we insert elements into the vector using the method push_back. string word; while ( cin >> word ) //the number of words is unlimited. { svec.push_back(word); }

Insertion void push_back(const T& x); push_back Inserts an element with value x at the end of the controlled sequence. svec.push_back(str);

Size unsigned int size(); Returns the length of the controlled sequence (how many items it contains). unsigned int size = svec.size();

Class Exercise 1 Write a program that read integers from the user, sorts them, and print the result.

Solving the problem  Easy way to read input.  A “place” to store the input  A way to sort the stored input.

Using STL int main() { int input; vector ivec; /* rest of code */ }

STL - Input while ( cin >> input ) ivec.push_back(input);

STL - Sorting sort(ivec.begin(), ivec.end()); Sort Prototype: void sort(Iterator first, Iterator last);

STL - Output for ( int i = 0; i < ivec.size(); ++i ) cout << ivec[i] << " "; cout << endl; vector ::iterator it; for ( it = ivec.begin(); it != ivec.end(); ++it ) cout ::iterator it; for ( it = ivec.begin(); it != ivec.end(); ++it ) cout << *it << " "; cout << endl; Or (more recommended)

STL - Include files #include // I/O #include // container #include // sorting //using namespace std;

Putting it all together int main() { int input; vector ivec; // input while (cin >> input ) ivec.push_back(input); // sorting sort(ivec.begin(), ivec.end()); // output vector ::iterator it; for ( it = ivec.begin(); it != ivec.end(); ++it ) { cout ivec; // input while (cin >> input ) ivec.push_back(input); // sorting sort(ivec.begin(), ivec.end()); // output vector ::iterator it; for ( it = ivec.begin(); it != ivec.end(); ++it ) { cout << *it << " "; } cout << endl; return 0; }

Operations on vector  iterator begin(); begin  iterator end(); end  bool empty(); empty  void push_back(const T& x); push_back  iterator erase(iterator it); erase  iterator erase(iterator first, iterator last); erase  void clear(); clear  ….

Standard C++ Library Part II

Last Time  String abstraction  Containers - vector

Today  Map  pair  copy algorithm

Employee class Employee { public: // Constructors...: Employee () {} Employee () {} Employee (const string& name) : _name(name) {} Employee (const string& name) : _name(name) {} // Member functions...: void set_salary(int salary) {_salary = salary; } void set_salary(int salary) {_salary = salary; } int salary() const { return _salary; } int salary() const { return _salary; } void set_name(const string& name) { _name = name; } void set_name(const string& name) { _name = name; } const string& name() const { return _name;} // … private: int _salary; const string& name() const { return _name;} // … private: int _salary; string _name; };

Locating an Employee Save all employees in a vector. When we need to find a specific employee: go over all employees until you find one that its name matches the requested name. Bad solution - not efficient!

Solution: Map – Associative Array  Most useful when we want to store (and possibly modify) an associated value.  We provide a key/value pair. The key serves as an index into the map, the value serves as the data to be stored.  Insertion/find operation - O(logn)

Using Map Have a map, where the key will be the employee name and the value – the employee object. name employee. stringclass Employee map employees;

Populating a Map void main() { map employees; map employees; string name(“Eti”); Employee *employee; string name(“Eti”); Employee *employee; employee = new Employee(name); employee = new Employee(name); //insetrion //insetrion employees[name] = employee; employees[name] = employee;}

Locating an Employee map employees; Looking for an employee named Eti : //find Employee *eti = employees[“Eti”]; //or map ::iterator iter = employees.find(“Eti”); The returned value is an iterator to map. If “Eti” exists on map, it points to this value, otherwise, it returns the end() iterator of map.

Iterating Across a Map Printing all map contents. map ::iterator it; for ( it = employees.begin(); it != employees.end(); ++it ) { cout ::iterator it; for ( it = employees.begin(); it != employees.end(); ++it ) { cout << ??? }

Iterators Provide a general way for accessing each element in sequential (vector, list) or associative (map, set) containers.

Pointer Semantics Let iter be an iterator then : ++iter (or iter++) Advances the iterator to the next element ++iter (or iter++) Advances the iterator to the next element *iter Returns the value of the element addressed by the iterator. *iter Returns the value of the element addressed by the iterator.

Begin and End Each container provide a begin() and end() member functions. begin() Returns an iterator that addresses the first element of the container. begin() Returns an iterator that addresses the first element of the container. end() returns an iterator that addresses 1 past the last element. end() returns an iterator that addresses 1 past the last element.

Iterating Over Containers Iterating over the elements of any container type. for ( iter = container.begin(); iter != container.end(); ++iter ) { // do something with the element }

Map Iterators map ::iterator iter; What type of element iter does addresses? The key ? The value ? It addresses a key/value pair.

Pair Stores a pair of objects, first of type T 1, and second of type T 2. struct pair { T1 first; T2 second; };

Our Pair In our example iter addresses a pair In our example iter addresses a pair Element. Accessing the name (key) iter->first Accessing the Employee* (value) iter->second

Printing the Salary for ( iter = employees.begin(); iter != employees.end(); ++iter ) { cout first second)->salary(); }

Example Output alon 3300 dafna eyal 5000 nurit 6750

Map Sorting Scheme map holds its content sorted by key. We would like to sort the map using another sorting scheme. (by salary)

Map Sorting Problem Problem: Since map already holds the elements sorted, we can’t sort them. Solution: Copy the elements to a container where we can control the sorting scheme.

Copy copy(Iterator first, Iterator last, Iterator where); Copy from ‘first’ to ‘last’ into ‘where’. int ia[] = { 0, 1, 1, 2, 3, 5, 5, 8 }; vector ivec1(ia, ia + 8 ), ivec2; int ia[] = { 0, 1, 1, 2, 3, 5, 5, 8 }; vector ivec1(ia, ia + 8 ), ivec2; //... //... copy(ivec1.begin(),ivec1.end(), copy(ivec1.begin(),ivec1.end(), ivec2.begin() ); ivec2.begin() );

The Problem  ivec2 has been allocated no space.  The copy algorithm uses assignment to copy each element value.  copy will fail, because there is no space available.

The Solution: use back_inserter() Causes the container’s push_back operation to be invoked. The argument to back_inserter is the container itself. // ok. copy now inserts using ivec2.push_back() copy(ivec1.begin(),ivec1.end(), back_inserter(ivec2) );

Inserter iterators. Puts an algorithm into an “insert mode” rather than “over write mode”.  iter = causes an insertion at that position, (instead of overwriting).

Employee copy map employees; vector > evec; copy( employees.begin(), employees.end(), back_inserter( evec ) ); Now it works!!!

Sort Formal definition : void sort(Iterator first, Iterator last);

Sort sort( Iterator begin, Iterator end ); Example: vector ivec; // Fill ivec with integers … sort(ivec.begin(), ivec.end())

Inside Sort  Sort uses operator  to sort two elements.  What happens when sorting is meaningful, but no operator  is defined ?

The meaning of operator  What does it mean to write : pair p1, p2; if ( p1 p1, p2; if ( p1 < p2 ) { … }

The meaning of operator  No operator  is defined between two pairs. How can we sort a vector of pairs ?

Sorting Function Define a function that knows how to sort these elements, and make the sort algorithm use it.

lessThen Function bool lessThen(pair &l, pair &r ) { return (l.second)->Salary() Salary() }

Using lessThen vector > evec; // Use lessThen to sort the vector. sort(evec.begin(), evec.end(), lessThen); pointer to function

Sorted by Salary alon 3300 eyal 5000 nurit 6750 dafna 10000

Putting it all Together bool lessThen( pair &p1, pair &p2 ) { … } int main() { map employees; /* Populate the map. */ vector > employeeVec; copy( employees.begin(), employees.end(), back_inserter( employeeVec ) ); sort( employeeVec.begin(), employeeVec.end(), lessThen ); vector >::iterator it; for ( it = …; it != employeeVec.end(); ++it ) { cout second)->getName() second)->getSalary() second)->getName() second)->getSalary() << endl; } return 0;}