Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.

Slides:



Advertisements
Similar presentations
Main Index Contents 11 Main Index Contents Shifting blocks of elements… Shifting blocks of elements… Model of a list object… Model of a list object… Sample.
Advertisements

1 STL Map & Multimap Ford & Topp Chapter 11 Josuttis Sections: 6.5 & 6.6 CSE Lecture 15 – Maps.
LINKED QUEUES P LINKED QUEUE OBJECT Introduction Introduction again, the problem with the previous example of queues is that we are working.
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
Week 5 - Associative Containers: sets and maps. 2 2 Main Index Main Index Content s Content s Container Types Sequence Containers Adapter Containers Associative.
Engineering Problem Solving With C++ An Object Based Approach Chapter 6 One-Dimensional Arrays.
Main Index Contents 11 Main Index Contents Model for a Queue Model for a Queue The Queue The Queue ADTQueue ADT (3 slides) Queue ADT Radix Sort Radix Sort.
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.
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.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
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:
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Data Structures Using C++ 2E
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
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
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
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.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
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++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
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.
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.
Adapted from Data Structures with C++ using STL: Ford, Topp CS 362: Queues Dr. Nazli Mollah Overview of Lecture  Introduction  The Queue ADT  The Radix.
Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
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.
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.
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.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 20: Container classes; strings.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
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.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 19: Container classes; strings.
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.
Object-Oriented Programming (OOP) Lecture No. 41
CS212: Object Oriented Analysis and Design
CSCE 210 Data Structures and Algorithms
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
Object Oriented Programming COP3330 / CGS5409
Associative Structures
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
priority_queue<T>
Lecture 8 : Intro. to STL (Standard Template Library)
Standard Template Library
Standard Template Library
An Introduction to STL.
Chapter 3 Lists, Stacks, and Queues
8.3 Vectors Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
The List Container and Iterators
Presentation transcript:

Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp

Intro to STL (Standard Template Library) container classes Data structure: a container of data that supports insertion, deletion, and updating operations on the stored data. Classical data structures such as vector; queue, deque, and priority queue; list, stack; set and multiset, map and multimap have been pre-programmed as template classes and integrated into C++ as STL.

Categories of STL container classes Sequence containers Adapter containers associative containers vectorstackset and multiset dequequeuemap and multimap listpriority-queue Sequence containers: data elements stored in linear order. Adapter container: contains another container (usually a sequence container) as its underlying storage structure. Associative container: stores elements by keys such as Id numbers.

Illustrations of STL sequence containers Linked list Vertor

Illustrations of STL adapter containers (using sequence containers as the storage)

Illustrations of STL associative containers

A quick review of C++ arrays An array is a fixed-size collection of values of the same data type. An array is a container that stores the n (size) elements in a contiguous block of memory. Once declared, n cannot be changed. Array name is associated with the address of the array. So when an array is passed to a function, the size (or the number of elements that need to be processed) of the array must also be passed. Directly assigning one array to another of same size and type are not allows: arrayA = arrayB; // syntax error!

The vector container class characteristics Similar to a one-dimensional array: use index for direct access. Can dynamically grow and contract (remember size of an conventional array cannot be changed once it is declared!) vector is a STL class, it contains many useful member functions size(), pushback(), back(), popback, resize(), empty(), etc.

A simple example // Vector function writeVetor( ) template void writeVctor(const vector &v ) { int i, n = v.size( );// size( ) is a member function for (i = 0; i < n; i++) cout << v[i] << '\t';// identical to an array cout << endl; }

Examples of how vector objects are declared and initialized // without initialization vector v(5);// vector of size 5 containing 0's vector s(10); // size 10, each element contain null string // with initialization vector line(80, 'A'); // 80 characters, each initialized to 'A' vector t(5, time(12,30, 0));// 5 elements with initial value 12:30:00 // initialization from an array int a[5] = {1, 2, 3, 4, 5};// array with initial values vector v(a, a + 5);// initial values copied from the array a // notice a + 5 is the address just past the end // of array a // initialization without specifying the size, the initial size will be defaulted to 0 vector dblv; vector s2;

Vector member function push_back( ) and pop_back( ) v.push_back(55); v.pop_back( );

The sizeof( ) operator and back( ) member function char vowel[ ] = {'a'. 'e', 'i', 'o', 'u'}; int vowelSize = sizeof(vowel)/sizeof(char); vector v(vowel, vowel + vowelSize); cout << v.back( );// output 'u' v.push_back('w');// add 'w' to end of v v.back( ) = 'y';// change back from 'w' to 'y'

Example: start with an empty vector and build a list with input (values of double type) from the user vector list;// declares an empty list double data; cout << “Enter a list of real values: “; cin >> data; while(data != -99) { list.push_back(data); cin >> data; }

Example: the pairing of back( ) and pop_back( ) int a[ ] = {1, 2, 3, 4, 5, 6}; int aSize = sizeof(a) / sizeof(int); vector v(a, a + aSize); while(!v.empty( )) { cout << v.back( ) << '\t'; v.pop.back( ); }// output:

Resizing a vector with resize( ) member function int a[ ] = {1, 2, 3, 4, 5}; int aSize = sizeof(a) / sizeof(int); vector v(a, a + aSize);// size = 5 v.resize(2 * aSize); // size = 10, "fill" value is 0 v.resize(4);// size = 4, data is lost v.resize(10, 1);// size = 10. fill value is 1

How is the vector class defined: the vector class abstraction The constructors vector( ); // default constructor creates an empty vector. vector(int n, const T& value = T( )); /* creates a vector with n elements, each have the specified value. If value is omitted, the elements are filled with the default value for type T. Type T must have a default constructor, a nd the default value of type T is specified by the notation T( ). */ vector(T *first, T *last); /* initialize the vector using the address range [first, last).

The abstraction of the vector class continued The member functions or operations T &back( );// returns the value of the item at the rear of the vector // Pre-condition: the vector must contain at least one element. const T &back( );// const version of back( ); bool empty( ) const;// returns true if vector is empty, false otherwise T &operator[ ](int i); // allows element at index i to be retrieved or modified. const T &operator[ ](int i); // const version of T &operator[ ](int i); void push_back(const T &value); /* Post-condition: a new element is added to the rear and the size of the vector is increased by 1. */

The abstraction of the vector class continued The member functions or operations (continued) void pop_back( ); /* removes the item at the rear; Precondition: the vector is not empty Post condition: the size of the vector is decreased by 1. */ void resize(int n, const T & fill = T( )); /* modifies the size of the vector; if the size is increased, new elements with value fill are added to the rear of the vector. If the value is decreased, the original values at the front are retained. Post-condition: the vector has size n. */ int size( ) const; /* returns the number of elements in the vector. */

A simple application: join two vectors together template void join(vector &v1, const vector &v2) { int i, sizev2 = v2.size( ); for (i = 0; i < sizev2; i++) v1.push_back(v2[i]); }

The insertion sort

//insertionSort(): // sort a vector of type T using insertion sort template void insertionSort(vector & v) { int i, j, n = v.size(); T temp; // place v[i] into the sublist v[0]... v[i-1], 1 <= i < n, // so it is in the correct position

The insertion sort continued for (i = 1; i < n; i++) {// index j scans down list from v[i] looking for //correct position to locate target. assigns it to v[j] j = i; temp = v[i]; // locate insertion point by scanning downward as // long as temp < v[j-1] and we have not // encountered the beginning of the list

The insertion sort continued while (j > 0 && temp < v[j-1]) { // shift elements up list to make room for insertion v[j] = v[j-1]; j--; } // the location is found; insert temp v[j] = temp; }

Running time of insertion sort requires (n-1) passes for pass i, the insertion occurs in the sublist v[0] to v[i-1] and requires an average of i/2 comparisions. Thus, T(n) = 1 / 2 + 2/2 + … + (n-2)/2 + (n-1)/2 = n(n-1)/4 or the running time is O(n 2 ). The best case occurs when the list is already in order, the total number of comparson T(n) = n-1, leading to O(n) running time. The worst case occurs when the list is in descending order and T(n) = n(n-1)/2 or O(n 2 ) running time. The insertion sort exhibits the best performance among the quadratic sorting algorithms when the list is partially ordered.

Another vector application: joining three sorted sublists // File: prg4_2.cpp // the program generates 12 random integers in the range // 100 to 999. add each number value to vector vSmall if // value < 400, to vector vMedium if 400 <= value < 700 // and to vLarge if 700 <= value < apply the insertion // sort to order each vector. use join() so that vSmall is // the concatenation of the three vectors. sort the final list // in vSmall by using the insertion sort. display the initial // set of elements in each vector and the final sorted list // by calling writeVector()

Another vector application: joining three sorted sublists continued #include #include "d_random.h"// for randomNumber #include "d_sort.h"// for insertionSort() #include "d_util.h"// for writeVector() using namespace std; // attach vB onto the end of vA template void join (vector &vA, const vector & vB);

Another vector application: joining three sorted sublists continued int main() { // declare 3 integer vectors vector vSmall, vMedium, vLarge; // use a random number generator randomNumber rnd; int i, value; for (i = 0; i < 12; i++) { value = rnd.random(900) + 100; if (value < 400) vSmall.push_back(value); else if (value < 700 ) vMedium.push_back(value); else vLarge.push_back(value); }

Another vector application: joining three sorted sublists continued // sort the vector of integers in the range // 100 <= n < 400 and output insertionSort(vSmall); cout << "Small: "; writeVector(vSmall); // sort the vector of integers in the range // 400 <= n < 700 and output insertionSort(vMedium); cout << "Medium: "; writeVector(vMedium);

Another vector application: joining three sorted sublists continued // sort the vector of integers in the range // 700 <= n < 1000 and output insertionSort(vLarge); cout << "Large: "; writeVector(vLarge); // join vMedium onto the end of vSmall join(vSmall, vMedium); // join vLarge onto the end of the modified vSmall join(vSmall, vLarge); // output the new vector cout << "Sorted: "; writeVector(vSmall); return 0; }

Another vector application: joining three sorted sublists continued template void join (vector &vA, const vector & vB) { // capture the size of vB in sizeB int i, sizeB = vB.size(); // use index i to access the elements of vB and push_back() // to add the elements to the rear of vA for (i = 0; i < sizeB; i++) vA.push_back(vB[i]); } /* Run: Small: Medium: Large: Sorted:

The matrix class Because of its importance in science and engineering applications, matrix class has been included in the C++ STL. Matrix is implemented as a vector of vectors: vector > mat; /* the outer vector corresponds to rows of the matrix, the elements in the inner vector of type T correspond to the column entries for each vector row. For example, mat[0] is the vector of column entries corresponding to row 0, etc. Note that there must be a space between the closing angle brackets > > or is will be interpreted as >> which is the extraction operator or right shift operator in bit manipulation. */