Rossella Lau Lecture 2, DCO20105, Semester A,2005-6 DCO 20105 Data structures and algorithms  Lecture 2: Vector  Array and vector  Internal structure.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Beginning C++ Through Game Programming, Second Edition
Searching Kruse and Ryba Ch and 9.6. Problem: Search We are given a list of records. Each record has an associated key. Give efficient algorithm.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Arrays.
Rossella Lau Lecture 11, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 11: Template and Operator overload  Template.
Standard Containers: Vectors
Rossella Lau Lecture 5, DCO20105, Semester A, DCO Data structures and algorithms  Lecture 5: Deque Comparison of sequence containers  Deque.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
Rossella Lau Lecture 1, DCO20105, Semester A, DCO Data structures and algorithms  Lecture 1: Introduction What this course is about:  Data.
Rossella Lau Lecture 3, DCO20105, Semester A, DCO Data structures and algorithms  Lecture 3: Basics of Linked List  C++ pointer revision.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Rossella Lau Lecture 5, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 5: Class construction  Encapsulation 
Rossella Lau Lecture 4, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 4: Basic containers  Array: fundamental.
Rossella Lau Lecture 4, DCO20105, Semester A, DCO Data structures and algorithms  Lecture 4: C++ and list  Usage of Vector and List  C++
C++ for Engineers and Scientists Third Edition
Rossella Lau Lecture 1, DCO20105, Semester A, DCO Data structures and algorithms  Lecture 1: Introduction What this course is about:  Data.
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
Review of C++ Programming Part II Sheng-Fang Huang.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
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
2 Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Containers Overview and Class Vector
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Chapter 2 ARRAYS.
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
Generic Programming Using the C++ Standard Template Library.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
Pointers OVERVIEW.
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.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
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)
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Vectors Updated 11/4/2003 by Kip Irvine. Copyright Kip Irvine Overview What is a vector? Declaring vector objects Inserting and removing items Using.
Vectors the better arrays. Why Vectors l vectors are implemented as a class (a template to be exact) l they serve the same purpose as arrays but using.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
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.
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.
Standard Template Library
CS212: Object Oriented Analysis and Design
Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Introduction to Linked Lists
Object Oriented Programming COP3330 / CGS5409
Data structures and algorithms
Lists - I The List ADT.
Lists - I The List ADT.
the Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
Chapter 3 Lists, Stacks, and Queues
Presentation transcript:

Rossella Lau Lecture 2, DCO20105, Semester A, DCO Data structures and algorithms  Lecture 2: Vector  Array and vector  Internal structure of a vector  How data is stored in a vector  Process on a vector  Application considerations -- By Rossella Lau

Rossella Lau Lecture 2, DCO20105, Semester A, A traditional container allowing storage of multiple occurrences of data  A truck of memory is assigned and data can be stored into its slots.  The number of slots is the size of the array and once that is defined, its size cannot be changed  An array uses an index to identify (access) its element  Data can be stored in any slot of an array but usually are stored from the first slot and new datum is appended at the end Array … …

Rossella Lau Lecture 2, DCO20105, Semester A, Main Index Contents C++ Arrays (Ford’s slide: 4-12) 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.

Rossella Lau Lecture 2, DCO20105, Semester A, Typical operations on an array  An array allows elements to be added/deleted at any arbitrary position  “Shift” operations are required when elements are inserted between elements and deleted at a position before the last element (Text book slides: 1:7)

Rossella Lau Lecture 2, DCO20105, Semester A, Arrays in programming language  Usually supported by programming languages without using any library functions  An array can be static or dynamic  The size of a static array is determined at compilation time while the size of a dynamic array can be determined during execution

Rossella Lau Lecture 2, DCO20105, Semester A, // static arrays int arrayA[20]; int arrayB[]={1,2,3,4}; Examples of C arrays  An array and a pointer are the same  A static array id is a constant pointer while dynamic array, the pointer, can point to any new value (array)  The storage occupied by a dynamic array should be released before the program is terminated. // dynamic array int *array; …… array = new int[size]; …… delete[] array;

Rossella Lau Lecture 2, DCO20105, Semester A, Main Index Contents Evaluating an Array as a Container (Ford’s slide: 4-13)  The size of an array is fixed at the time of its declaration and cannot be changed during the runtime.  An array cannot report its size. A separate integer variable is required in order to keep track of its size.  C++ arrays do not allow the assignment of one array to another.  The copying of an array requires the generation of a loop structure with the array size as an upper bound.

Rossella Lau Lecture 2, DCO20105, Semester A, Exception handling of array process  A programmer should take care to avoid overflow, when elements needed to be stored are more than the slots of an array  A programmer should take care all the “shift” operations are of an insert or a delete action

Rossella Lau Lecture 2, DCO20105, Semester A, Vector  As O-O concept was matured and there were O-O languages, class Vector usually comes with a language’s library for use as an array  A vector encapsulates all array’s related housekeeping processes to save programmers’ some work in taking care of the overflow (while doing an insertion), shift operations, etc.

Rossella Lau Lecture 2, DCO20105, Semester A, class Vector{ private: int *array; size_t size; size_t capacity; public: …… }; A typical vector class – Structure  A language supported array  capacity stores the number of slots in the vector (the array size)  size stores the number of slots used (usually the slots are occupied contiguously)

Rossella Lau Lecture 2, DCO20105, Semester A, A typical vector class – Methods  at(i) – returns the item at slot i  insert(i,item) – inserts item before slot i and automatically resize the array if the array is “full”  erase(i) – removes the element at slot i and may shift elements from (i+i..n-1) to (i..n-2)  resize(i) – makes the vector to have an array with size i class Vector{ private: …… public: int at(size_t i); void insert(size_t i, int item); void erase(size_t i); void resize(size_t); size_t size(); size_t capacity(); …… };

Rossella Lau Lecture 2, DCO20105, Semester A, However …  Consider the sample class vector  if the objects stored on the array are not integers, but strings, rational numbers, or student records, we may need to create many classes. class Vector{ int *array; size_t size; size_t capacity; …… }; class VectorStr{ string *array; size_t size; size_t capacity; …… }; class VectorStd{ Student *array; size_t size; size_t capacity; …… };   Absolutely terrible for maintenance

Rossella Lau Lecture 2, DCO20105, Semester A, Vector intArray; Templates in C++  In C++, type parameter supports a template class / function to be written as it can be of any data type  Rewrite class Vector to a template class  Whenever instantiating a Vector object, a type must be specified class Vector{ int *array; size_t size; size_t capacity; …… }; template <class T> T Vector strArray; Vector stdArray;

Rossella Lau Lecture 2, DCO20105, Semester A, C++ Vector  Vector in C++ is a template class in which it supports  typical array operations: getting space for an array (instantiating a vector object), identifying an element, storing data, removing data; etc  housekeeping together with iterator operations in order to allow some generic algorithms to be applied on

Rossella Lau Lecture 2, DCO20105, Semester A, Getting a vector  Syntax: Ford’s slide 4:15-16  E.g., // declare a vector with number of default slots vector studentNumber;  Ford’s slide 4:22 // vector of size 5 containing the integer // value 0 vector intVector(5); // vector of size 10; each element // contains the empty string vector strVector(10);

Rossella Lau Lecture 2, DCO20105, Semester A, Identifying elements  Syntax: Ford’s slide 4:18  To identify elements in a vector is the same as the way for an array: Ford’s slide 14

Rossella Lau Lecture 2, DCO20105, Semester A, Storing data to a vector  push_back() provides a quick action to store an item after the occupied slot (the last datum) can cause the vector to re-size if there is not enough room  insert() places an item before a specified position is inefficient but necessary if a particular order is required  []= ( e.g., v[i]=23; ) places an item at a specified position overwrites the value if the position is occupied may cause error if the specified position is invalid

Rossella Lau Lecture 2, DCO20105, Semester A, Examples for storing data  Storing data into an empty vector  Storing data into a pre-defined vector: vector numbers; for( i = 0; i < SIZE; i++ ) numbers.push_back(i); vector numbers(SIZE); for( i = 0; i < SIZE; i++ ) numbers[i] = i;

Rossella Lau Lecture 2, DCO20105, Semester A, Remove an item  Remove an item:  pop_back() To remove the last item, shifting is not needed  erase() To remove an item through an iterator, but shifting is required E.g., OrderItem.h in application bookShop v2.0 (without a delete flag)  Alternatively, each element can include a flag to indicate if an item is deleted to avoid shift operations  E.g., OrderItem.h in application bookShop (v 1.0)

Rossella Lau Lecture 2, DCO20105, Semester A, Elements with delete flags  It is efficient to remove an item in the middle – just a mark rather than shifts  The trade-off is an additional space is required and subsequently, whenever a slot is visited, the slot must be checked  The slot marked “delete” can be used again or let it be “removed” forever  Re-use may cause more checking … … TT

Rossella Lau Lecture 2, DCO20105, Semester A, Other vector operations  Accessors:  back() to return the value of the last item  size() to return the number of contiguous used slots  capacity() to return the number of slots in the vector  Housekeeping:  resize() to re-allocate the capacity and size of the vector  Care should be taken when instantiating an object with the constructor Vector(SIZE). The system assumes SIZE of slots have been used. If it is not the case, remember to reset its size to 0 by using resize(0).  ……

Rossella Lau Lecture 2, DCO20105, Semester A, Vector traversal with index  It is similar to traverse an array; e.g.: Traversal: to “visit” each element in a data structure; typical operations such as: to print all elements from a data structure, to find an item from a data structure …… vector studentID; …… for (int i=0; ; i < studentID.size(); i++) cout << studentID[i] << “ “; ……

Rossella Lau Lecture 2, DCO20105, Semester A, Vector traversal with Iterator Remember that  Iterator is similar to a pointer referring to an element  each STL container supports an iterator to traverse the container itself  begin() returns the iterator which points to the first element  end() returns the iterator which refers to to pass-the-end, not the last element …… vector studentID; vector ::iterator it; …… for (it=studentID.begin(); i !=studentID.end(); it++) cout << *it << “ “; ……

Rossella Lau Lecture 2, DCO20105, Semester A, Searching an item from a vector with find() find() is a generic algorithm which can be applied to every STL’s container Typical usage : typedef vector ::iterator It; // for simpler declaration It it = find(v.begin(), v.end(), x); // returns an iterator if ( it != v.end() ) // found

Rossella Lau Lecture 2, DCO20105, Semester A, Example of find()  The linear search we used to have: (w/o delete flag)  Use the generic algorithm find() with iterator; int getItem(string publicationCode) const { int i=0; for (; i<items.size() &&((items[i].getPublication().getCode() != publicationCode); i++); return items.size() == 0 ? -1 : i < items.size() ? i : -1; } pair getItem(string const& publicationCode) { It result = find(items.begin(),items.end(), publicationCode); return result == items.end()? pair (false, result) : pair (true, result); }

Rossella Lau Lecture 2, DCO20105, Semester A, Better searching method find() uses linear searching and the efficiency is not good. When a container can provide random (direct) position access, such as an array or a vector, sort can be applied first and then binary search can take place  sort (v.begin(), v.end()); binary_search(v.begin(), v.end(), target); // returns boolean

Rossella Lau Lecture 2, DCO20105, Semester A, Binary search methods  To return the iterator pointing to the position of the target being searched, the following can be used:  It lbIt = lower_bound(v.begin(), v.end(), target);  It ubIt = upper_bound(v.begin(), v.end(), target);  pair range = equal_range(v.begin, v.end(), target); target= …… lbItubIt range.first==range.second

Rossella Lau Lecture 2, DCO20105, Semester A, Operator Overload and generic algorithm  Note that generic algorithm used to require operator overload  In the last example, two operator overload operations are required:  orderItem == publicationCode (in OrderItem.h)  publication == publicationCode (in Publication.h)

Rossella Lau Lecture 2, DCO20105, Semester A, Better? Not always!  Storing data to a vector  push_back() provides a quick action to store an item  insert() is inefficient but necessary if a particular order is required (save operations for a sort)  Finding elements from a vector  Sequential search is inefficient but an order is not required; i.e., push_back() can be used for storing data  Binary search is efficient but requiring a sorted order: i.e., insert() must be used for storing data

Rossella Lau Lecture 2, DCO20105, Semester A, Application considerations Stable and long data stream required a lot of searches but few insert/erase operations are better to be sorted for binary search  Short data stream with few searches but many insert operations are better to use push_back() and sequential search

Rossella Lau Lecture 2, DCO20105, Semester A, Summary  Vector is a sequential storage container which encapsulates an array and its housekeeping process as a class to simplify programmers’ work  It is the simplest storage structure to store data in contiguous slots with a trade off of that inefficient insert/erase operations  In C++, vector, in the STL, is a template class which allows data in a vector to be of any data type  STL’s vector supports a variety of functions for data storage  Together with generic algorithms, iterator, and operator overload, many popular vector traversal functions, such as search, are ready for use  Operations’ usage should depend on a particular application

Rossella Lau Lecture 2, DCO20105, Semester A, Reference  Ford: 1.8, 2.4, 3.5, 4  Lecture 12 of DCO10105  STL online references     Example programs: OrderItem.h, Order.h, Catalog.h in the application BookShop v END --