Vectors Updated 11/4/2003 by Kip Irvine. Copyright Kip Irvine 2003. Overview What is a vector? Declaring vector objects Inserting and removing items Using.

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

Beginning C++ Through Game Programming, Second Edition
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
1 Standard Containers: Lists Gordon College Resource:
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Copyright Kip Irvine 2001, all rights reserved. Vectors (Vectores) Agustin J. González Versión Original de Kip Irvine ELO329.
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.
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.
Lesson 7 Arrays CS 1 Lesson 7 -- John Cole1. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
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
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.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
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,
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Lecture 11 Standard Template Library Lists Iterators Sets Maps.
Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.
Lecture 7 : Intro. to STL (Standard Template Library)
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
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.
Chapter 7 Arrays Csc 125 Introduction to C++. Topics Arrays Hold Multiple Values Array Operations Arrays as function arguments Two-dimensional arrays.
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.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Introduction to Data Structure, Fall 2006 Slide- 1 California State University, Fresno Introduction to Data Structure Chapter 4 Ming Li Department of Computer.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Copyright © 2012 Pearson Education, Inc. Chapter 7: Arrays.
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.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
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.
CS212: Object Oriented Analysis and Design
Vectors Holds a set of elements, like an array
CSCE 210 Data Structures and Algorithms
Standard Template Library (STL)
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Advanced Program Design with C++
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Object Oriented Programming COP3330 / CGS5409
Vectors the better arrays.
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Standard Version of Starting Out with C++, 4th Edition
Lists - I The List ADT.
Lists - I The List ADT.
Iterators and STL Containers
7 Arrays.
§ § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊
STL List.
Lesson 25 Miscellaneous Topics
the Standard Template Library
Chapter 3 Lists, Stacks, and Queues
8.3 Vectors Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
§ § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § § ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊
The List Container and Iterators
STL List.
A dictionary lookup mechanism
Presentation transcript:

Vectors Updated 11/4/2003 by Kip Irvine

Copyright Kip Irvine Overview What is a vector? Declaring vector objects Inserting and removing items Using subscripts Getting and changing the size Preallocating space Passing vectors to functions Vector return values

Copyright Kip Irvine What is a Vector? From the Standard C++ Library documentation: A vector is a sequence that supports random access to elements, constant time insertion and removal of elements at the end, and linear time insertion and removal of elements at the beginning or in the middle. The number of elements in a vector may vary dynamically; memory management is automatic. Vector is the simplest of the STL container classes, and in many cases the most efficient.

Copyright Kip Irvine Declaring Vector Objects #include vector scores(20); vector names; vector busyFlags(5); vector classRoll(50); You can declare a vector of any type can be empty or it can have a size

Copyright Kip Irvine Inserting and Removing Items push_back(item) inserts an item pop_back() removes an item, but does not return it to the caller

Copyright Kip Irvine Inserting and Removing Items vector temps; temps.push_back( 88.5 ); temps.push_back( 87.2 ); temps.push_back( 82.1 ); // now the vector contains elements in // positions [0], [1], and [2]. // remove the last element: temps.pop_back();

Copyright Kip Irvine Using Subscripts vector scores; scores[0] = 25; // crashes! scores.push_back( 15 ); scores[0] = 25; // ok now For any subscript n, the following must be true: 0 <= n < size() The C++ vector class does not check index ranges.

Copyright Kip Irvine Constructor A vector constructor can take an integer parameter that sets the size Each element can be optionally initialized by the constructor vector names(10); vector scores(10, 0); // all 10 elements contain zero vector backup( scores ); // make a copy of a vector

Copyright Kip Irvine Getting/Changing the Size size() returns the number of elements in the vector empty() returns true if size == 0 push_back() increases the size by 1 pop_back() decreases the size by 1 resize() changes the size Examples:

Copyright Kip Irvine Getting and Changing the Size vector names( 10 ); cout << names.size( ); // 10 names.push_back( "Sam" ); cout << names.size( ); // 11 names.resize( 15 ); // size = 15 names.pop_back( ); // size = 14

Copyright Kip Irvine Automatic Expansion If push_back() discovers that the vector is full, the vector automatically doubles in size separate copy of the vector is made, with considerable runtime overhead

Copyright Kip Irvine Reserving Space reserve(n) sets aside space for expansion without affecting the value returned by size() Use reserve() to make push_back() more efficient

Copyright Kip Irvine Vectors in Classes class Scores { public: double at(int index) const; // return the score at index private: vector m_vScores; }; A vector should be encapsulated in a class, to provide adequate error checking

Copyright Kip Irvine Vectors in Classes double at( int index ) const { if( index >= 0 && index < m_vScores.size( ) ) return m_vScores[ index ]; else return 0.0; } The following function performs range checking:

Copyright Kip Irvine Vectors in Classes class MyClass { public: private: vector myVec( 20 ); // error! vector myVec; // ok }; A size value cannot be passed to the vector constructor in a class definition:

Copyright Kip Irvine Vectors in Classes MyClass::MyClass( int theSize ) : myVec( theSize ) { } Instead, space for the vector can be reserved in the constructor implementation by using a member initializer:

Copyright Kip Irvine Vectors in Classes MyClass::MyClass( int theSize ) { myVec.reserve( theSize ); // size() still returns 0 } Or, space for the vector can be reserved in the constructor implementation:

Copyright Kip Irvine Vectors in Classes MyClass::MyClass( int theSize ) { myVec.resize( theSize ); // size() returns value of theSize } Or, the vector can be resized, causing empty elements to be inserted:

Copyright Kip Irvine Passing Vectors to Functions double calcAverage( const vector & scores ) { double avg = 0; //... return avg; } Always pass vectors by reference Use const if the vector will not be modified

Copyright Kip Irvine Filling a Vector void fillRandom( vector & vList ) { int i; for( i = 0; i < vList.size( ); i++ ) { int n = rand( ) % 100; vList[i] = n; } Example: fill a vector with random integers between 0 and 99:

Copyright Kip Irvine Vector Return Values vector makeRandomVector( int count ) { vector list( count ); // set the size for( int i = 0; i < count; i++ ) { list[i] = rand( ); } return list; // return a copy } You can declare a vector inside a function and return a copy of the vector: but copying incurs runtime overhead!

Copyright Kip Irvine Vector Return Values // sample call: vector Z = makeRandomVector( 25 );

Copyright Kip Irvine Sorting a Vector #include vector items; sort( items.begin( ), items.end( ) ); Assume that the vector contains items whose type/class is predefined in C++ The sort( ) function belongs to the algorithm library begin( ) points to the first element, and end( ) points one position beyond the last element

Copyright Kip Irvine Iterators vector items; vector ::iterator I; I = items.begin(); // first number cout << *I << endl; // display the number An iterator is a pointer to a vector element that can be moved forward or backward through the vector elements dereference the iterator to access the element it points to

Copyright Kip Irvine Sorting Using Iterators #include vector items; vector ::iterator I1; vector ::iterator I2; I1 = items.begin( ); I2 = items.end( ); sort( I1, I2 ); You can pass iterators to the sort() function:

Copyright Kip Irvine Sorting User-Defined Types vector cop3337; sort( cop3337.begin( ), cop3337.end( ) ); Sorting a vector containing your own class types is slightly more advanced You must overload the < operator in your class (see next panel)

Copyright Kip Irvine Overloading the < Operator class Student { public: bool operator <(const Student & S2) { return m_sID < S2.m_sID; } private: string m_sID; string m_sLastName; };

Copyright Kip Irvine Common Vector Operations vector items; // Reverse the order reverse( items.begin( ), items.end( ) ); // Randomly shuffle the order random_shuffle( items.begin( ), items.end( ) ); // Accumulate the sum #include int sum = accumulate( items.begin( ), items.end( ), 0 );

Copyright Kip Irvine Find/Remove Lowest Value vector items; vector ::iterator I; // find lowest value I = min_element( items.begin( ),items.end( ) ); // erase item pointed to by iterator I items.erase( I );

Copyright Kip Irvine The End