Vector. Vector Class. class Vector { public: typedef unsigned int size_type;

Similar documents
STL: C++ Standard Library

Templates and Vectors

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

CS197c: Programming in C++

vector<int> second (4,100); // four ints with value 100 vector<int> third (second.begin(),second.end()); // iterating through second

Standard Library Reference

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

Implementing vector<>

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

Chapter 17: Linked Lists

CS11 Advanced C++ Spring 2018 Lecture 2

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008

The Standard Template Library Classes

Data Structures and Algorithms

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation

Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Pointers. Pointers. Pointers (cont) CS 217

Faculty of Information and Communication Technologies

CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation

Program vector.cc (continued)

I source_beg, source_end; // defines a range of values in a source container // defines the beginning of a range in a destination container

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Vectors. A Computer Science Tapestry 8.1

Chapter 17: Linked Lists

1. The term STL stands for?

Computer Science II CSci 1200 Lecture 24 C++ Inheritance and Polymorphism

List, Stack, and Queues

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

Due Date: See Blackboard

Patterns: Working with Arrays

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11

Programming with Haiku

Containers in C++ and Java

Intermediate Programming, Spring 2017*

การทดลองท 8_2 Editor Buffer Array Implementation

Standard-Library Exception Safety

1 Short Answer (5 Points Each)

Concepts for the C++0x Standard Library: Containers

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

C++ Programming Fundamentals

Dynamic Data Structures

int main(){ int main(){ We want to understand this in depth! std::vector<int> v(10,0); // Vector of length 10

Data Structures Lecture 3 Order Notation and Recursion

STL Quick Reference for CS 241

Structuur van Computerprogramma s 2

19. Dynamic Data Structures II

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

use static size for this buffer

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

C++_ MARKS 40 MIN

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

Chapter 9. Operator Overloading. Dr Ahmed Rafat

Computer Science II CSci 1200 Lecture 8 Iterators; Programming Examples

1. Write the number of the definition on the right next to the term it defines. (a) copy 4

Pointers. Pointer References

Higher Secondary Second Year COMPUTER SCIENCE Model question Paper - 3

Overview. Part II: Containers and Algorithms. Overview. Overview

Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

ADT: Design & Implementation

PIC 10A. Lecture 19: More about Vectors

This chapter serves mainly to gather and organize information about iterators. Some new concepts are also introduced for completeness.

We look back... #include <iostream> #include <vector>

STL Containers, Part I

Chapter 17 vector and Free Store

Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file.

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Chapter 17 vector and Free Store

List Iterators. Lecture 27 Section Robb T. Koether. Hampden-Sydney College. Wed, Apr 8, 2015

Computer Science II CSci 1200 Test 1 Overview and Practice

LECTURE 03 LINKED LIST

Introduction to Computer Science Midterm 3 Fall, Points

pointers & references

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Exercise 6.2 A generic container class

Array Elements as Function Parameters

Consider the program...

STL. Zoltán Porkoláb: C++11/14 1

Writing Generic Functions. Lecture 20 Hartmut Kaiser hkaiser/fall_2013/csc1254.html

DATA STRUCTURES AND ALGORITHMS LECTURE 08 QUEUES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD

CSCI 104. Rafael Ferreira da Silva. Slides adapted from: Mark Redekopp and David Kempe

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

AIMS Embedded Systems Programming MT 2017

B16 Object Oriented Programming

Contract Programming For C++0x

Template based set of collection classes STL collection types (container types)

CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions

List Iterators. Lecture 34 Section Robb T. Koether. Hampden-Sydney College. Wed, Apr 24, 2013

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

Critique this Code. Hint: It will crash badly! (Next slide please ) 2011 Fawzi Emad, Computer Science Department, UMCP

Chapter 19 Vector, templates, and exceptions

Transcription:

Vector Arrays in C++ must be pre-allocated to accomodate the maximum number of elements. Should an application attempt to add more than this number, the program may abort, or alter storage of adjacent variables in memory. Let's encapsulate arrays in a Vector class. This class will preallocate a fixed number of elements, but grow as needed to accomodate increasing demands. In addition we'll provide range checking and throw an exception if subscripting exceeds the bounds of the array. To further encapsulate the array, we'll implement an iterator for sequential access. Vector Class class Vector { typedef unsigned int size_type; // default constructor Vector() { vcapacity = 100; vsize = 0; // destructor ~Vector() { delete [] v; // return size of vector int size() const { return vsize; // returns capacity of vector without reallocation int capacity() const { return vcapacity; // subscripting operators double& operator[](size_type i) { return v[i]; // subscripting operators with range checking double& at(size_type i) { if (i >= vsize) throw logic_error("out of range"); return v[i]; size_type vsize; // number of element in vector size_type vcapacity; // capacity of vector without reallocation double *v; // pointer to first element of vector ; // usage: Vector a; Vector::size_type i; // "i" is actually an unsigned int for (i = 0; i < a.size(); i++) cout << a[i]; a[0] = 5; cout << a.at(0); // modify element a[0] // output a[0] with range checking

The Vector class assumes we are storing doubles in the array. Private member v is a pointer to the array, vsize indicates the number of elements actually stored in the vector, and vcapacity the number of available elements. The constructor allocates 100 elements by default, and the subscripting operators allow access to each element. The subscripting operators, [ ] and at, assume that the element being addressed already exists. To add and delete elements from the vector we'll include two new member functions: push_back and pop_back. // add a new element to vector void Vector::push_back(double x) { if (vsize >= vcapacity) { // reallocate vector vcapacity *= 2; double *t = new double[vcapacity]; t[i] = v[i]; delete [] v; v = t; v[vsize++] = x; // delete last element in a vector void Vector::pop_back() { vsize--; Function push_back adds a new element at the end of the vector. First it checks to see if there's enough room in the vector. If not, then it allocates another vector, twice the capacity as the original, copies elements to the new vector, then deletes the original. Function pop_back simply decrements the size of the vector. No error checking is done. To complete functionality, a copy constructor and assignment operator are included. // copy constructor Vector::Vector(const Vector& a) { vcapacity = a.vcapacity; vsize = a.vsize; v[i] = a.v[i]; // assignment operator Vector& Vector::operator=(const Vector& rhs) { if (this == &rhs) return *this; delete [] v; vcapacity = rhs.vcapacity; vsize = rhs.vsize; v[i] = rhs.v[i]; return *this;

Vector Iterator An iterator is an object that allows sequential access to a class's data. We will implement the following iterator: Vector::iterator i; for (i = v.begin(); i!= v.end(); ++i) It helps if you view iterators as pointers to data in the class. In other words, we could rewrite the above statements, using a pointer, as follows: double *i; for (i = &v[0]; i!= &v[n]; ++i) To support this notion, let's define the following begin and end member functions: typedef VectorIterator iterator; // iterator to first item Vector::iterator Vector::begin() const { return v; // iterator to one past last item Vector::iterator Vector::end() const { return v + vsize; We'll implement class VectorIterator to define the iterator itself. To support the return values of begin and end we'll include a constructor in the VectorIterator that converts "double *" to a VectorIterator. class VectorIterator { // constructor VectorIterator() { p = 0; // convert pointer to iterator (used for begin/end) VectorIterator(double *v) { p = v; double *p; ; // pointer to element associated with iterator

Let's repeat the original examples that uses an iterator, Vector::iterator i; for (i = v.begin(); i!= v.end(); ++i) and the corresponding example that uses pointers: double *i; for (i = &v[0]; i!= &v[n]; ++i) We've defined a begin member function that returns &v[0], and an end member function that returns &v[n]. To assign one iterator to another, such as in the statement i = v.begin(); we'll rely on the default bitwise copy behavior of the assignment operator. To compare, increment, and dereference iterators, we'll add the following member functions to VectorIterator: class VectorIterator { // compare iterators bool operator!=(vector::iterator i) const { return i.p!= p; // preincrement operator VectorIterator& operator++() { p = p + 1; return *this; // return value associated with iterator double& operator*() const { return *p; double *p; // pointer to element associated with iterator ;

Finally we'll add an erase member function to the Vector class. This will allow us to delete any item in the vector using an iterator. e.g., Vector a; a.push_back(1); a.push_back(3); a.push_back(5); a.erase(a.begin()); // delete element "1" Code for the erase function follows. We currently don't have a member function that converts an iterator to a pointer, so we'll use the unusual combination of &* to obtain a reference. // delete element designated by iterator Vector::iterator Vector::erase(Vector::iterator i) { // compute subscript of item to erase double *p = &*i; int ss = (int)(p - v); // shift all elements above ss down one notch vsize--; for (size_type j = ss; j < vsize; j++) v[j] = v[j+1]; // return pointer to successor return p;