Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.

Slides:



Advertisements
Similar presentations
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Advertisements

C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Starting Out with C++, 3 rd Edition 1 Chapter 16 – Exceptions, Templates, and the Standard Template Library (STL) Exceptions are used to signal errors.
Beginning C++ Through Game Programming, Second Edition
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT5: Array (1D and 2D) CS2311 Computer Programming.
List Chapter 9 : Arrays and Vectors Mechanism for representing lists.
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
More on the STL vector list stack queue priority_queue.
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.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
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.
C++ for Engineers and Scientists Third Edition
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.
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.
Object Oriented Data Structures
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:
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
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
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Arrays and Containers Mechanism for representing lists.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
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)
C++ STL CSCI 3110.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
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.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 12 – Data Structures – Trees Sorting Algorithms.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
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.
 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.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Lecture 7 : Intro. to STL (Standard Template Library)
A gentle introduction to the standard template library (STL) Some references:
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
The Standard Template Library Container Classes Version 1.0.
CSIS 3401 Introduction to Data structures and algorithms.
The Sorting Methods Lecture Notes 10. Sorts Many programs will execute more efficiently if the data they process is sorted before processing begins. –
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.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 20: Container classes; strings.
Introduction to Data Structure, Fall 2006 Slide- 1 California State University, Fresno Introduction to Data Structure Chapter 4 Ming Li Department of Computer.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
The Linear and Binary Search and more Lecture Notes 9.
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.
Object-Oriented Programming (OOP) Lecture No. 41
CS212: Object Oriented Analysis and Design
Standard Template Library (STL)
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
priority_queue<T>
Mechanism for representing lists
COMS 261 Computer Science I
Lists - I The List ADT.
Lists - I The List ADT.
COMS 261 Computer Science I
Chapter 3 Lists, Stacks, and Queues
Presentation transcript:

Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan

Vectors First-class mechanism for representing lists

Standard Template Library What is it? Collection of container types and algorithms supporting basic data structures What is a container? A generic list representation allowing programmers to specify which types of elements their particular lists hold  Uses the C++ template mechanism Have we seen this library before? String class is part of the STL

Sequences deque, list, and vector  Vector supports efficient random-access to elements STL Container Classes Associative map, set Adapters priority_queue, queue, and stack

Provides list representation comparable in efficiency to arrays Vector Class Properties First-class type Efficient subscripting is possible Indices are in the range 0 … size of list - 1 List size is dynamic Can add items as we need them Index checking is possible Through a member function Iterators Efficient sequential access

Construction Basic construction vector List; Example vector A; // 0 ints vector B; // 0 floats vector C;// 0 Rationals Base element type Container name

Construction Basic construction vector List(SizeExpression); Example vector A(10); // 10 ints vector B(20); // 20 floats vector C(5);// 5 Rationals int n = PromptAndRead(); vector D(n); // n ints Base element type Container name Number of elements to be default constructed

Construction Basic construction vector List(SizeExpression, Value); Example vector A(10, 3); // 10 3s vector B(20, 0.2); // s Rational r(2/3); vector C(5, r); // 5 2/3s Base element type Container name Number of elements to be default constructed Initial value

Example #include using namespace std; int main() { vector A(4, 0); // A: A.resize(8, 2); // A: vector B(3, 1); // B: for (int i = 0; i < B.size(); ++i) { A[i] = B[i] + 2; } // A: A = B; // A: return 0; }

Some Vector Constructors vector() The default constructor creates a vector of zero length vector(size_type n, const T &val = T()) Explicit constructor creates a vector of length n with each element initialized to val vector(const T &V) The copy constructor creates a vector that is a duplicate of vector V.  Shallow copy!

Vector Interface size_type size() const Returns the number of elements in the vector cout << A.size(); // display 3 bool empty() const Returns true if there are no elements in the vector; otherwise, it returns false if (A.empty()) { //...

Vector Interface vector & operator = (const vector &V) The member assignment operator makes its vector representation an exact duplicate of vector V.  “Shallow copy” (will see what this means later) The modified vector is returned vector A(4, 0); // A: vector B(3, 1); // B: A = B; // A: 1 1 1

Example vector A(4, 0); // A: const vector B(4, 0); // B: for (int i = 0; i < A.size(); ++i) { A[i] = 3; } // A: for (int i = 0; i < A.size(); ++i) { cout << A[i] << endl; // lvalue cout << B[i] << endl; // rvalue }

Vector.at(i) vector A(4, 0); // A: for (int i = 0; i <= A.size(); ++i) { A[i] = 3; } // A: ?? for (int i = 0; i <= A.size(); ++i) { A.at(i) = 3; } // program terminates // (“exception”) when i is 4 vector.at(i) If i is in bounds, returns a reference to element i of the vector; otherwise, throws an exception (vector[i] behaves like array[i])

Vector Interface void resize(size_type s, T val = T()) The number of elements in the vector is now s.  To achieve this size, elements are deleted or added as necessary Deletions if any are performed at the end Additions if any are performed at the end New elements have value val vector A(4, 0); // A: A.resize(8, 2); // A: A.resize(3,1); // A: 0 0 0

Function Examples void GetList(vector &A) { int n = 0; while ((n > A[n])) { ++n; } A.resize(n); // Cut off empty part of vector } vector MyList(3); cout << "Enter numbers: "; GetList(MyList);

Examples void PutList(const vector &A) { for (int i = 0; i < A.size(); ++i) { cout << A[i] << endl; } cout << "Your numbers: "; PutList(MyList)

Vector Interface pop_back() Removes the last element of the vector push_back(const T &val) Inserts a copy of val after the last element of the vector

Example void GetValues(vector &A) { A.resize(0); int Val; while (cin >> Val) { A.push_back(Val); // A grows as required! } vector List; cout << "Enter numbers: "; GetValues(List);

Iterators Iterator is a pointer to an element Really pointer abstraction Mechanism for sequentially accessing the elements in the list Alternative to subscripting There is an iterator type for each kind of vector list Notes Algorithm component of STL uses iterators Code using iterators rather than subscripting can often be reused by other objects using different container representations

Vector Interface iterator begin() Returns an iterator that points to the first element of the vector iterator end() Returns an iterator that points to immediately beyond the last element of the vector vector C(4); // C: C[0] = 0; C[1] = 1; C[2] = 2; C[3] = 3; vector ::iterator p = C.begin(); vector ::iterator q = C.end();

Iterators To avoid unwieldy syntax programmers typically use typedef statements to create simple iterator type names typedef vector ::iterator iterator; typedef vector ::reverse_iterator reverse_iterator; typedef vector ::const_reference const_reference; vector C(4); // C: iterator p = C.begin(); iterator q = C.end();

Iterator Operators * dereferencing operator Produces a reference to the object to which the iterator p points *p ++ point to next element in list Iterator p now points to the element that followed the previous element to which p points ++p -- point to previous element in list Iterator p now points to the element that preceded the previous element to which p points -- p

typedef vector ::iterator iterator; typedef vector ::reverse_iterator reverse_iterator; vector List(3); List[0] = 100; List[1] = 101; List[0] = 102; iterator p = List.begin(); cout << *p; // p; cout << *p; // p; cout << *p; // 100 reverse_iterator q = List.rbegin(); cout << *q; // q; cout << *q; // q; cout << *q; // 102

Example: vector of strings Consider vector A; which is set in the following manner A[0]: "A" A[1]: "list" A[2]: "of" A[3]: "words" A[4]: "to" A[5]: "be" A[6]: "read."

Counting o’s The following counts number of o’s within A count = 0; for (int i = 0; i < A.size(); ++i) { for (int j = 0; A[i].size(); ++j) { if (A[i][j] == 'o') { ++count; } To reference j th character of A[i] we need double subscripts Size of A[i] Size of A

Two-Dimensional List E.g. 2 dimensional array: int A[n][n] For 2 dimensional vectors, consider definition vector > A; Then A is a vector > It is a vector of vectors A[i] is a vector i can vary from 0 to A.size() - 1 A[i][j] is a int j can vary from 0 to A[i].size() - 1

Common Sorting Techniques Selection sort On ith iteration place the ith smallest element in the ith list location Bubble sort Iteratively pass through the list and examining adjacent pairs of elements and if necessary swap them to put them in order. Repeat the process until no swaps are necessary

Common Sorting Techniques Insertion sort On ith iteration place the ith element with respect to the i-1 previous elements  In text Quick sort Divide the list into sublists such that every element in the left sublist <= to every element in the right sublist. Repeat the Quick sort process on the sublists  In text

SelectionSort void SelectionSort(int A[], int n) { for (int i = 0; i < n-1; ++i) { int k = i; // Find smallest element in rest of array for (int j = i + 1; j < n; ++j) { if (A[j] < A[k]) k = j; } // And now move it to the front if (i != k) swap(A[k], A[i]); }

SelectionSort Using vector Class void SelectionSort(vector &A) { int n = A.size(); for (int i = 0; i < n); ++i) { int k = i; for (int j = i + 1; j < n; ++j) { if (A[j] < A[k]) k = j; } if (i != k) swap(A[k], A[i]); }

InsertionSort void InsertionSort(vector &A) { for (int i = 1; i < A.size(); ++i) { // assert: A[0]..A[i-1] is sorted // code below inserts A[i] in above int key = A[i] int j = i - 1; // Shift larger elements to the right while ((j > 0) && (A[j] > key)) { A[j+1] = A[j]; j = j – 1; } A[j+1] = key }

QuickSort Divide the list into sublists such that every element in the left sublist <= to every element in the right sublist Repeat the QuickSort process on the sublists void QuickSort(vector &A, int left, int right) { if (left < right) { Pivot(A, left, right); int k = Partition(A, left, right); QuickSort(A, left, k-1); QuickSort(A, k+1, right); } Optional: not required for CS101

Picking The Pivot Element void Pivot(vector &A, int left, int right) { if (A[left] > A[right]) { Swap(A[left], A[right]); } Optional: not required for CS101

Decomposing Into Sublists int Partition(vector &A, int left, int right) { char pivot = A[left]; int i = left; int j = right+1; do { do ++i; while (A[i] < pivot); do --j; while (A[j] > pivot); if (i < j) { Swap(A[i], A[j]); } } while (i < j); Swap(A[j], A[left]); return j; } Optional: not required for CS101

Sorting Q W E R T Y U I O P Q W E R T Y U I O P I O E P T Y U R W Q E O I P T Y U R W Q E I O P T Y U R W Q E I O P Q Y U R W T E I O P Q R T U W Y Optional: not required for CS101