18 – Sequential Containers

Slides:



Advertisements
Similar presentations
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
Advertisements

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.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
CS Oct 2006 Chap 6. Functions General form; type Name ( parameters ) { … return value ; }
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.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
11 COS220 Concepts of PLs AUBG, COS dept Lecture 36 OOP The STL Standard Template Library Reference: MS Developer Studio, Visual C++, Lafore, Chap 15 STL,
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
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)
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.
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.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Lecture 8-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
1 Chapter 13-1 Applied Arrays: Lists and Strings Dale/Weems.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
CS212: Object Oriented Analysis and Design Lecture 28: Functors.
Review. Problem 1 What is the output of the following piece of code void increment(int x) { x++; } int main() { int y = 10; increment(y); cout
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
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.
Lecture 36 OOP The STL Standard Template Library
Motivation for Generic Programming in C++
CS212: Object Oriented Analysis and Design
Jordi Cortadella, Ricard Gavaldà, Fernando Orejas
Andy Wang Object Oriented Programming in C++ COP 3330
Programming with ANSI C ++
Exceptions, Templates, and the Standard Template Library (STL)
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
Standard Template Library (STL)
Starting Out with C++ Early Objects Eighth Edition
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
Friday, February 16, 2018 Announcements… For Today… 4.5-, pgs. 252
Monday, April 2, 2018 Announcements… For Today… For Next Time…
Sorting Chapter 10.
Chapter 9 – Sets and Maps 9.1 Associative Container
10.6 Shell Sort: A Better Insertion
Function and class templates
Associative Structures
Lab 03 - Iterator.
A Sorted, Unique Key Container
CS212: Object Oriented Analysis and Design
14 – Sequential Containers
Andy Wang Object Oriented Programming in C++ COP 3330
Elements are always copied when they are put into a container
CMSC 341 Skip Lists.
Doubly Linked List Implementation
Standard Version of Starting Out with C++, 4th Edition
Engineering Problem Solving with C++, Etter
Lists - I The List ADT.
Lists - I The List ADT.
Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library (STL)
C++ Templates L03 - Iterator 10 – Iterator.
CIS 199 Final Review.
Standard Template Library
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
14 – Sequential Containers
C++ Templates L04 - Iterator 10 – Iterator.
Standard Template Library
Presentation transcript:

18 – Sequential Containers 4.7 Implementation of a Double- Linked List Class 4.8 Application of the list Class 4.9 Standard Library Containers 4.10 Standard Library Algorithms and Function Objects 18 – Sequential Containers

Attendance Quiz #17 Sequential Containers

Tip #18: Improve Success Ratio Sequential Containers Do the tough stuff first. Think more, code less. For big stuff, get someone’s brain wrapped around it. Under promise, over deliver. When something breaks, look at your assumptions. Before you begin coding, decide how you are going to test it. Trust your team, but ask to see. Learn how to listen. Don’t whine! (ie. Clear the Bozo bit.) No Coding after midnight!

4.8, pgs. 285-286 4.8 Application of the list Class Case Study: Maintaining an Ordered List 4.8, pgs. 285-286

Application of the list Class Sequential Containers Problem We want to maintain this list so that it will be in alphabetical order even after students have added and dropped the course. Analysis Develop a general Ordered_List class that can be used to store any group of objects that can be compared using the less-than operator. Solution Write a new Ordered_List class. Inherit the C++ list class to create a new Ordered_List class and over-ride list functions (not recommended.) Or create a new Ordered_List class that uses a C++ list to store the items. Use list functions where appropriate (delegation). Write new function where needed.

Ordered Linked List Insertion Sequential Containers Algorithm for Insertion Find the first item in the list that is greater than or equal to the item to be inserted Create an iterator that starts at the beginning of the list while the iterator is not at the end and the item at the iterator position is less than the item to be inserted Advance the iterator Insert the new item before this one.

Delegation Code for Insertion Use Delegation for the Other Functions Sequential Containers Code for Insertion Inside a declaration or a definition of a template, typename can be used to declare that a dependent name is a type. void insert(const Item_Type& an_item) { typename std::list<Item_Type>::iterator itr = a_list.begin(); while (itr != a_list.end() && *itr < an_item) ++itr; // itr points to the first item >= an_item or the end a_list.insert(itr, an_item); } Use Delegation for the Other Functions void remove(const Item_Type& item) { a_list.remove(item); } A delegate is a class or method that wraps a pointer or reference to an object instance, a member method of that object's class to be called on that object instance, and provides a method to trigger that call.

4.9, pgs. 292-295 4.9 Standard Library Containers Common Features of Containers Sequences Associative Containers Vector Implementation Revisited 4.9, pgs. 292-295

Standard Library Containers Sequential Containers The C++ standard uses the term container to represent a class that can contain objects. The term concept is used to represent the set of common requirements for a container: C++ defines a common interface for all containers and then splits the set of containers into sequential containers and associative containers. Common requirements unique to these subsets are also defined and the individual containers have their own additional requirements. Although a list and a vector have several member functions in common, they are not polymorphically, but can be used interchangeably by generic algorithms. In a sequential container, at any given time each element has a particular position relative to the other items in the container. items in a sequence (ie., a vector or a list) follow some linear arrangement. In an associative container, on the other hand, there is no particular position for each item in the container. An item is accessed by its value, rather than by its position.

4.10 Standard Library Algorithms and Function Objects The find Function The Algorithm Library The swap Function Function Objects 4.10, pgs. 297-307

The Algorithm Library Sequential Containers The standard library contains many useful template functions defined in the header <algorithm>, that use a pair of iterators to define the sequence of input values. Some of them also take function objects as parameters The template functions perform fairly standard operations on containers, such as Applying the same function to each element (for_each) Copying values from one container to another (copy) Searching a container for a target value (find, find_if) Sorting a container (sort) Summing container values (accumulate) Apply function to container objects (transform) This fragment copies the contents of a_list into a_vector: a_vector.resize(a_list.size()); copy(a_list.begin(), a_list.end(), a_vector.begin());

template<typename II, typename F> Function Behavior template<typename II, typename F> F for_each(II first, II last, F fun) Applies the function fun to each object in the sequence. The function fun is not supposed to modify its argument. The iterator argument II is required to be an input iterator. This means that the sequence is traversed only once. template<typename II, typename T> II find(II first, II last, T target) Finds the first occurrence of target in the sequence. If not found, last is returned. template<typename II, typename P> II find_if(II first, II last, P pred) Finds the first occurrence of an item in the sequence for which function pred returns true. If not found, last is returned. template<typename FI> FI min_element(FI first, FI last) FI max_element(FI first, FI last) Finds the min/max element in the sequence FI; first..last. FI is a forward iterator. template<typename II, typename OI> OI copy(II first, II last, OI result) Copies the sequence first..last into result..(result + (last - first)). II is an input iterator, and OI is an output iterator. template<typename II, typename OI, typename OP> OI transform(II first, II last, OI result, OP op) Applies op to each element of the sequence first..last and places the result in result..(result + (last - first)). template<typename II1, typename II2, typename OI, typename BOP> OI transform(II1 first1, II1 last1, II2 first2, OI result, BOP bin_op) Applies bin_op to each pair of elements of the sequences first1..last1 and first2..(first2 + (last1 - first1)) and places the result in result..(result + (last1 - first1))

template<typename T> void swap(T& a, T& b) Function Behavior template<typename T> void swap(T& a, T& b) Exchanges the contents of a and b. template<typename BI> void reverse(BI first, BI last) Reverses the sequence first..last. BI is a bidirectional iterator. template<typename RI> void random_shuffle(RI first, RI last) Randomly rearranges the contents of first..last. RI is a random-access iterator. void sort(RI first, RI last) Sorts the contents of first..last based on the less-than operator applied to pairs of elements. template<typename RI, typename COMP> void sort(RI first, RI last, COMP comp) Sorts the contents of first..last based on the binary operator COMP (a function operator). COMP is a function class that takes two arguments and returns a bool. template<typename II, typename T> T accumulate(II first, II last, T init) Computes init plus the sum of the elements in first..last. Note that this function is defined in the header <numeric>. template<typename II1, typename II2> bool equal(II1 first1, II1 last1, II2 first2) template<typename II1, typename II2, typename BP> bool equal(II1 first1, II1 last2, II2 first2, BP pred) Compares each element in the sequence first1..last1 to the corresponding elements in the sequence first2..first2 + (last1 - first1). If they are all equal, then this returns true. The second form uses the function object pred to perform the comparison.

Function Objects

Data field divisor stores the number we want to divide by Function Objects Sequential Containers The function call operator (operator()) can be overloaded by a class. A class that overloads this operator is called a function class and an object of such a class is called a function object (or functor.) As an example, we may want to find a value divisible by another value. We can create a function class Divisible_By whose constructor takes the divisor as an argument: Data field divisor stores the number we want to divide by class Divisible_By { private: int divisor; public: Divisible_By(int d) : divisor(d) {} bool operator()(int x) return x % divisor == 0; } }; The definition of operator() tests the remainder resulting from the division of the function argument (int x) by the value of divisor The expression Divisible_By(3) creates a function object that returns true if the argument passed to it is divisible by 3 The expression Divisible_By(5) creates a function object that tests for integers divisible by 5

Function Objects Sequential Containers template<typename II, typename P> II find_if(II first, II last, P pred) Finds the first occurrence of an item in the sequence for which function pred returns true. If not found, last is returned. Template parameter II is a placeholder for an input iterator; template parameter P is a placeholder for a function class with an operator() that returns a bool value. // Find first number divisible by 3 in list_1. list<int>::iterator = iter; iter = find_if(list_1.begin(), list_1.end(), Divisible_By(3)); if (iter != list_1.end()) cout << "The first number divisible by 3 is " << *iter << endl; else cout << "There are no numbers divisible by 3" <<endl; // Find first number divisible by 5 in list_1. iter = find_if(list_1.begin(), list_1.end(), Divisible_By(5)); if (iter != list_1.end()) cout << "The first number divisible by 5 is " << *iter << endl; else cout << "There are no numbers divisible by 5" << endl;

Write a template Functor named Matcher such that function calls to a Matcher object returns true if same, else false. // Define templated Matcher object. // Instantiate Matcher object isMatch. // Use isMatch to test if the number n is 5. template <typename T> class Matcher { private: T target; public: Matcher(T m) : target(m) {} bool operator()(T x) { return x == target; } }; Matcher<int> isMatch(5); if (isMatch(n)) cout << n << " == 5" << endl; else cout << n << " != 5" << endl;