Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

Slides:



Advertisements
Similar presentations
Lists: An internal look
Advertisements

SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
Introduction to Programming Lecture 39. Copy Constructor.
Beginning C++ Through Game Programming, Second Edition
Week 5 - Associative Containers: sets and maps. 2 2 Main Index Main Index Content s Content s Container Types Sequence Containers Adapter Containers Associative.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Lecture 20 “Standard” Template Library. What is the Standard Template Library? A collection of C++ classes (templates) containers vectors lists stacks.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
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.
1 Fall Chapter 4 ADT Sorted List. 2 Goals Describe the Abstract Data Type Sorted List from three perspectives Implement the following Sorted List.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSE 332: C++ Associative Containers II Associative Containers’ Associated Types Associative containers declare additional types –A key_type gives the type.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Data Structures Using C++ 2E
CS352-Week 2. Topics Heap allocation References Pointers.
Data Structures.  Consider storing data for 100 employees by their Social Security Numbers (SSN)  SSN range: –  A fast search:
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Generic Programming Using the C++ Standard Template Library.
CS162 - Topic #11 Lecture: Recursion –Problem solving with recursion –Work through examples to get used to the recursive process Programming Project –Any.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
Data structures Abstract data types Java classes for Data structures and ADTs.
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.
Pointers, Variables, and Memory. Variables and Pointers When you declare a variable, memory is allocated to store a value. A pointer can be used to hold.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
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.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
1 Chapter 1 C++ Templates Sections 1.6 and Templates Type-independent patterns that can work with multiple data types –Generic programming –Code.
11/5/2016CS150 Introduction to Computer Science 1 Announcements  Assignment 6 due on Wednesday, December 3, 2003  Final Exam on Tuesday, December 9,
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Learning Objective  Standard Template Library.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
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.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
STL Associative Containers navigating by key. Pair Class aggregates values of two, possibly different, types used in associative containers defined in.
1 Linked Multiple Queues. 2 A real world example. Not in the book. Sometimes we have a fixed number of items that move around among a fixed set of queues.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
13/10/2016CS150 Introduction to Computer Science 1 Multidimensional Arrays  Arrays can have more than one column  Two dimensional arrays have two columns.
Vectors Updated 11/4/2003 by Kip Irvine. Copyright Kip Irvine Overview What is a vector? Declaring vector objects Inserting and removing items Using.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Main Index Contents 11 Main Index Contents Sets Defined by a key along with other data Sets Defined by a key along with other data Key-Value Data Key-Value.
CPSC 252 Tables / Maps / Dictionaries Page 1 Tables, Maps and Dictionaries A table (or map or dictionary) is a collection of key/value pairs. In general.
 Binary operators  Unary operators  Conversion Operators  Proxy Classes (simulating a reference) ▪ bitset example  Special operators  Indexing 
C++ Functions A bit of review (things we’ve covered so far)
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
C++ Standard Library.
Student Book An Introduction
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
Chapter 16-2 Linked Structures
Chapter 16 Linked Structures
Iterators and STL Containers
Standard C++ Library Part II.
An Introduction to STL.
A dictionary lookup mechanism
Standard Template Library
Presentation transcript:

Standard C++ Library Part II

Last Time b String abstraction b Containers - vector

Today b Map b pair b 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 b Most useful when we want to store (and possibly modify) an associated value. b We provide a key/value pair. The key serves as an index into the map, the value serves as the data to be stored. b 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 b Sort uses operator  to sort two elements. b 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;}