Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.

Slides:



Advertisements
Similar presentations
Passing Arrays to Functions Programming. COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 2 Passing Arrays as Parameters l Arrays are.
Advertisements

Standard Containers: Vectors
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
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.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Standard Template Library. Homework List HW will be posted on webpage Due Nov 15.
C++ for Engineers and Scientists Third Edition
CSE202: Lecture 16The Ohio State University1 Two Dimensional Arrays.
Templates and the STL.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic 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:
Data Structures Using C++ 2E
Copyright © 2012 Pearson Education, Inc. Chapter 8 Two Dimensional Arrays.
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
Matrices Jordi Cortadella Department of Computer Science.
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.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
Lecture Contents Arrays and Vectors: Concepts of array. Memory index of array. Defining and Initializing an array. Processing an array. Parsing an array.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type.
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:
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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
Lecture 7 : Intro. to STL (Standard Template Library)
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
More Array Access Examples Here is an example showing array access logic: const int MAXSTUDENTS = 100; int Test[MAXSTUDENTS]; int numStudents = 0;... //
Introduction to Programming (in C++) Multi-dimensional vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
 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.
Variables and memory addresses
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.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Lecture 7.  There are 2 types of libraries used by standard C++ The C standard library (math.h) and C++ The C++ standard template library  Allows us.
Multi-dimensional Array 1 Multi-dimensional array refers to an array with more than one index. It is a logical representation. On physical storage, the.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
 2003 Prentice Hall, Inc. All rights reserved vector Sequence Container Declarations –std::vector v; type : int, float, etc. Iterators –std::vector.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
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.
Chapter 8: Arrays. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Prof. Amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
Object-Oriented Programming (OOP) Lecture No. 41
CSCE 210 Data Structures and Algorithms
Motivation and Overview
Vectors Holds a set of elements, like an array
CSCE 210 Data Structures and Algorithms
CSCE 210 Data Structures and Algorithms
Collections Intro What is the STL? Templates, collections, & iterators
Two Dimensional Arrays
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Object Oriented Programming COP3330 / CGS5409
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Standard Version of Starting Out with C++, 4th Edition
Dr Tripty Singh Arrays.
Collections Intro What is the STL? Templates, collections, & iterators
Chapter 3 Lists, Stacks, and Queues
8.3 Vectors Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Presentation transcript:

Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class

Prof. amr Goneid, AUC2 The Vector Class

The Standard Template Library (STL) What is a Vector Declaring a Vector Size and Accessing Elements Adding and removing Elements Emptying a Vector Other Member Functions Iterators Vectors as Function Parameters or Types Vectors of Vectors Some Matrix Operations using Vectors of Vectors The Vector Class 3Prof. amr Goneid, AUC

STL is a collection of data types and algorithms that can be used in C++ programs. These data types and algorithms are not part of the C++ language but are user-defined. We will learn later how to create new Abstract Data Types (or ADT’s) through Classes. The vector class is one of the container classes in STL. The string class is also part of STL The Standard Template Library (STL) 4Prof. amr Goneid, AUC

5 What is a Vector The vector data type is a sequence (linear) container. Like the array, a vector holds a sequence of elements in contiguous memory locations. We can use the array access operator [ ] to access elements of a vector. Like the array, indices of elements are from 0 …Size-1 Prof. amr Goneid, AUC

6 What is a Vector Advantages over Arrays: You do not have to declare the number of elements in a vector, or if you do, the size can be a variable A vector can increase its size automatically to accommodate new data A vector can return the size of data stored in it. A function can return a vector type (functions cannot return array types, but only array parameters or pointers to arrays) Prof. amr Goneid, AUC

7 What is a Vector Disadvantages: Vectors take more space in memory Slower than arrays No 2-D or higher dimension vectors. Prof. amr Goneid, AUC

8 Declaring a Vector To use vectors in a program, we first include the vector class and use namespace std: #include using namespace std; Then, we declare a vector in the form: vector variablename; Examples: vector A;// No size is specified vector X(20);// starting Size is 20 floats vector S(10, ‘A’);// All 10 char initialized to ‘A’ vector Z(Y); // Y is a vector of double, Z initialized to Y values Prof. amr Goneid, AUC Template

9 Size and Accessing Elements To determine the size of a vector, we use the.size( ) member function, e.g. cin >> n; vector A(n);// Allocated size can be a variable int m = A.size( ); Elements 0.. size-1 can be accessed by [ ], e.g. void PrintValues (vector V) { for (int i = 0; i < V.size( ); i++) cout << V[i] << endl; } or use V.at(i) Notice that vector V is passed to the function by “value” Prof. amr Goneid, AUC

10 Size and Accessing Elements Two member functions exist for allowing access to the first and last elements in a vector. These are.front() and.back(). Examples: Assume vector v(20,0); // following statements are equivalent: int i = v.front(); int i = v[0]; int i = v.at(0); // following statements are equivalent: int j = v.back(); int j = v[v.size() ‐ 1]; int j = v.at(v.size() ‐ 1); Prof. amr Goneid, AUC

11 Adding and Removing Elements If we do not know in advance what size we want, we can declare a vector with no starting size and use push_back member function to add an element, e.g., vector array; array.reserve(10); // make room for 10 elements int k; while(k != 0){ cin >> k; array.push_back(k); }.push_back function adds an element to the end of the list..reserve(n) ensures that we have room for at least n elements Prof. amr Goneid, AUC

12 Adding and Removing Elements We Use the pop_back member function to remove the last element from a vector, e.g. array.pop_back(); Notice that push_back and pop_back will change the size of a vector (i.e. the number of elements stored). The capacity of a vector (the total number of slots allocated) will not change. To find the capacity of a vector, we use.capacity() function: vector X; X.reserve(10); X.push_back(999); cout << X.capacity() << ‘ ‘ << X.size(); // outputs 10 1 X.resize(15); //Increase the capacity to 15, size unchanged Prof. amr Goneid, AUC

13 Examples // Fill a vector with 10 random integers between 1 and 6 vector R(10,0); for(int i = 0; i < R.size(); i++) R[i] = rand() % 6 + 1; // Remove element at position (j), order does not matter j = 3; R[j] = R.back( ); R.pop_back( ); // Remove element at position (j), order matters j = 3; for (i = j+1; i < R.size( ); i++) R[i-1] = R[i]; R.pop_back( ); Prof. amr Goneid, AUC

14 Vector Assignment It is possible to assign a vector to another vector of the same type, e.g. vector A(4, 0); // A: vector B(3, 1); // B: A = B; // A: Notice that A becomes an exact copy of B Prof. amr Goneid, AUC

15 Clearing a Vector To completely clear the contents of a vector, use the clear member function, e.g. array.clear( ); After the statement above executes, the vector will be cleared of all its elements, size will be 0, capacity will not change. To test if a vector is empty, we use the.empty( ) function, e.g., if ( array.empty( )) cout << “Array has no elements \n”; Prof. amr Goneid, AUC

16 Other Member Functions Copy Constructor, e.g. vector values2(values1); values2 is declared as a vector of int and all elements of values1 (also a vector of int) are copied to values2.reverse( ): To reverse the sequence in a vector, e.g. array.reverse( );.swap: To swap the contents of two vectors, e.g. vector1.swap(vector2); Prof. amr Goneid, AUC

17 Iterators An iterator is a pointer to an element It can be used to access elements in a vector instead of subscribing There is an iterator type for each kind of vector The Algorithm component of STL uses iterators For vectors: iterator begin( ): returns an iterator to the first element iterator end( ): returns an iterator to one-past-the last element Prof. amr Goneid, AUC

18 Accessing Elements Examples: Assume vector v(20,0); // following statements are equivalent: int i = v.front(); int i = v[0]; int i = v.at(0); int i = *( v.begin( )); // following statements are equivalent: int j = v.back(); int j = v[v.size() ‐ 1]; int j = v.at(v.size() ‐ 1); int j = *(v.end( ) – 1); Prof. amr Goneid, AUC

19 Example on using Iterators vector A; vector ::iterator i; for(int k=1; k<6; k++) A.push_back(k*k); for(i = A.begin( ); i != A.end( ); i++) cout << (*i) << ‘ ‘; output: Prof. amr Goneid, AUC

20 Same Example using Pointers vector A; int *p, *q, *i; for(int k=1; k<6; k++) A.push_back(k*k); p = &A[0]; q = p+A.size( ); for(i = p; i != q; i++) cout << (*i) << ‘ ‘; output: Prof. amr Goneid, AUC

21 Vectors as Function Parameters or Types Vectors can be passed to functions by value or by reference Example passing by value: double average(vector v) { if (v.size() == 0) return 0; double sum = 0.0; for (int i = 0; i < v.size(); i++) sum = sum + v[i]; return sum / v.size(); } Prof. amr Goneid, AUC

22 Vectors as Function Parameters or Types Pass by reference when we want to modify the vector. Example passing by reference: // Insert an element at position p in a vector void insert (vector & v, int p, string s) { int last = v.size() - 1; v.push_back(v[last]); for (int i = last; i > p; i--) v[i] = v[i - 1]; v[p] = s; } Prof. amr Goneid, AUC

23 Vectors as Function Parameters or Types It is preferred to pass by reference. If vector elements are not to change, use const Example passing by reference: // Find index of maximum value in a vector // Assume vector to contain at least 1 element int index_of_Max(const vector & v) { int m = 0;int n = v.size( ); if (n > 1) for(int i = 1; i < n; i++) if (v[i] > v[m]) m = i; return m; } Prof. amr Goneid, AUC

24 Vectors as Function Parameters or Types A function may return a vector type Example: A function to receive an int vector and return a vector containing the positions of elements with zero values vector zerospos (const vector & v) { vector pos; for (int i = 0; i < v.size( ); i++) if ( v[i] == 0) pos.push_back(i); return pos; } Prof. amr Goneid, AUC

25 Vectors of Vectors The vectors of vectors can model 2-D arrays or matrices. To declare “amatrix” as an int vector with “Nrows” rows and “Ncols” columns: vector > amatrix(Nrows, std::vector (Ncols)); A more convenient way: typedef vector Row; typedef vector Matrix; typedef std::vector Cols; Now we declare: Matrix amatrix(Nrows, Cols(Ncols)); or a matrix of 3 rows and 4 columns: Matrix A(3,Cols(4)); Prof. amr Goneid, AUC

26 Vectors of Vectors Remember Nrows = A.size( ); Ncols = A[0].size( ); Prof. amr Goneid, AUC Matrix A A[0][2] A[1][2] A[2]: a whole row

27 Some Matrix Operations using Vectors of Vectors Adding Two Matrices Matrix matrix_sum(const Matrix& A, const Matrix& B) { // Pre: A and B are non-empty matrices of the same size // Post: returns A+B (sum of matrices) int nrows= A.size(); int ncols= A[0].size(); Matrix C(nrows, Cols(ncols)); for (int i = 0; i < nrows; i++) for (int j = 0; j < ncols; j++) C[i][j] = A[i][j] + B[i][j]; return C; } Prof. amr Goneid, AUC

28 Some Matrix Operations using Vectors of Vectors Multiplying Two Matrices Matrix multiply(const Matrix& A, const Matrix& B) { // Pre: A is a non-empty matrix of size N x L and // B is a non-empty matrix of size L x M // Post: returns C = A*B of size N x M int N= A.size(); int L = A[0].size( ); int M = B[0].size( ); Matrix C(N, Cols(M)); for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) int sum = 0; for (int k = 0; k < L; k++) sum = sum + A[i][k]*B[k][j]; C[i][j] = sum; return C; } Prof. amr Goneid, AUC

29 Some Matrix Operations using Vectors of Vectors Matrix Transpose Matrix transpose(const Matrix& A) { // Pre: A is a non-empty matrix of size N x M and // Post: returns C = transpose(A) of size M x N int N= A.size(); int M = A[0].size( ); Matrix C(M, Cols(N)); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) C[i][j] = A[j][i]; return C; } Prof. amr Goneid, AUC