CSE202: Lecture 18The Ohio State University1 C++ Vector Class.

Slides:



Advertisements
Similar presentations
C++ Basics March 10th. A C++ program //if necessary include headers //#include void main() { //variable declaration //read values input from user //computation.
Advertisements

Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
C++ Basics Prof. Shermane Austin. Learning Programming Language Basics Data Types – simple Expressions Relational and Logical Operators Conditional Statements.
Arrays Programming COMP102 Prog. Fundamentals I: Arrays / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g.,
Announcements Quiz 1 Next Week. int : Integer Range of Typically -32,768 to 32,767 (machine and compiler dependent) float : Real Number (i.e., integer.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Functions. COMP104 Lecture 13 / Slide 2 Review of Array: Bubble Sort for (j=0; j List[j+1]) swap(List[j], List[j+1]); }
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Multiple-Subscripted Array
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
C++ for Engineers and Scientists Third Edition
CSE202: Lecture 14The Ohio State University1 Arrays.
Simple Arrays Programming COMP104 Lecture 12 / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g., a collection.
Arrays.
Pointer Data Type and Pointer Variables
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
CSE1222: Lecture 3The Ohio State University1. Assignment Operations  The C++ assignment operator is: =  Examples: x = 3 * 5; y = x – 7; y = y + 4; Do.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Introduction to Programming Lecture 11. ARRAYS They are special kind of data type They are special kind of data type They are like data structures in.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
CMPSC 121- Spring 2015 Lecture 6 January 23, 2015.
Chapter 7 Arrays Csc 125 Introduction to C++. Topics Arrays Hold Multiple Values Array Operations Arrays as function arguments Two-dimensional arrays.
CSCI 161 Lecture 14 Martin van Bommel. New Structure Recall “average.cpp” program –Read in a list of numbers –Count them and sum them up –Calculate the.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Computer Programming Arrays 1. Question #1 2 Question Choose the correct answer..
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Lecture 2 Arrays. Topics 1 Arrays hold Multiple Values 2 Accessing Array Elements 3 Inputting and Displaying Array Contents 4 Array Initialization 5 Using.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
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.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
The Ohio State University
The Ohio State University
Programming fundamentals 2 Chapter 1:Array
7 Arrays.
Introduction to Programming
Arrays Kingdom of Saudi Arabia
Data type List Definition:
Standard Version of Starting Out with C++, 4th Edition
7 Arrays.
Arrays Arrays A few types Structures of related data items
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

CSE202: Lecture 18The Ohio State University1 C++ Vector Class

CSE202: Lecture 18The Ohio State University2 Limitations of Arrays The size of arrays must be a known constant prior to compile time. const MAX_SIZE(1000); double A[MAX_SIZE]; –Inefficient use of space e.g. A program needs enough storage to maintain 1000 real numbers, but on average, the user only enters 10 real elements. So, 900 * 8 bytes = 7200 bytes wasted on average. –Arrays cannot be resized in your program What if a user needs 2000 elements? Then a program with which has an array of size 1000 is useless!

CSE202: Lecture 18The Ohio State University3 Vector Class The C++ vector class is an alternative to using regular arrays, and helps us avoid array limitations. To use vectors, we must #include To declare a vector, the C++ syntax is vector varName;

CSE202: Lecture 18The Ohio State University4 Declaring Vectors (1) Something you can do with arrays: –Declare a vector, v1[], with 10 integers: vector v1(10); –Declare a vector, v2[], with 25 characters: vector v2(25);

CSE202: Lecture 18The Ohio State University5 Declaring Vectors (2) Vectors can do the following: –Declare the size of a vector using a variable cout << “How many strings need to be stored?”; cin >> n; vector v2(n); –Automatically initialize all elements of a vector: // initialize vector elements to -1 vector v4(5, -1.0); –Return the number of elements in the vector: for (int i = 0; i < v2.size(); i++) { v2[i] = i*i; }

CSE202: Lecture 18The Ohio State University6 logTable.cpp... const int SIZE(10); double log_table[SIZE]; // array of SIZE elements int n; cout << "Enter number of integers: "; cin >> n; while (n > SIZE) { cout << "Input error.“; cout << " Input must be less than or equal to " << SIZE << "." << endl; cout << "Enter number of integers: "; cin >> n; }

CSE202: Lecture 18The Ohio State University7 logTable.cpp (cont.) for (int i = 0; i < n; i++) { log_table[i] = log(double(i+1)); } for (int i = 0; i < n; i++) { cout << "log(" << i+1 << ") = " << log_table[i] << endl; } return 0; }

CSE202: Lecture 18The Ohio State University8 logTable2.cpp... #include... int n(0); cout << "Enter number of integers: "; cin >> n; vector log_table(n); // Note: Must have (n) for (int i = 0; i < log_table.size(); i++) { log_table[i] = log(double(i+1)); } for (int i = 0; i < log_table.size(); i++) { cout << "log(" << i+1 << ") = " << log_table[i] << endl; }...

CSE202: Lecture 18The Ohio State University9 reverse.cpp... const int ARRAY_SIZE(5); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements cout << "Enter list of " << ARRAY_SIZE << " integers: "; for (int i = 0; i < ARRAY_SIZE; i++) { cin >> list[i]; } cout << "Reverse list: "; for (int i = ARRAY_SIZE-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl;...

CSE202: Lecture 18The Ohio State University10... const int ARRAY_SIZE(5); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements cout << "Enter list of " << ARRAY_SIZE << " integers: "; for (int i = 0; i < ARRAY_SIZE; i++) { cin >> list[i]; } cout << "Reverse list: "; for (int i = ARRAY_SIZE-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl;... > reverse.exe Enter list of 5 integers: Reverse list:

CSE202: Lecture 18The Ohio State University11 reverse2.cpp... #include... int n(0); cout << "Enter length of list: "; cin >> n; vector list(n); cout << "Enter list of " << list.size() << " integers: "; for (int i = 0; i < list.size(); i++) { cin >> list[i]; } cout << "Reverse list: "; for (int i = list.size(); i > 0; i--) { cout << list[i-1] << " "; } cout << endl;...

CSE202: Lecture 18The Ohio State University12... int n(0); cout << "Enter length of list: "; cin >> n; vector list(n); cout << "Enter list of " << list.size() << " integers: "; for (int i = 0; i < list.size(); i++) { cin >> list[i]; } cout << "Reverse list: "; for (int i = list.size(); i > 0; i--) { cout << list[i-1] << " "; } cout << endl;... > reverse2.exe Enter length of list: 7 Enter list of 7 integers: Reverse list:

CSE202: Lecture 18The Ohio State University13 logTable2.cpp... #include... int n(0); cout << "Enter number of integers: "; cin >> n; vector log_table(n); // Note: Must have (n) for (int i = 0; i < log_table.size(); i++) { log_table[i] = log(double(i+1)); } for (int i = 0; i < log_table.size(); i++) { cout << "log(" << i+1 << ") = " << log_table[i] << endl; }...

CSE202: Lecture 18The Ohio State University14 logTableError.cpp... #include... int n(0); cout << "Enter number of integers: "; cin >> n; vector log_table; // Missing (n) for (int i = 0; i < log_table.size(); i++) { log_table[i] = log(double(i+1)); } for (int i = 0; i < log_table.size(); i++) { cout << "log(" << i+1 << ") = " << log_table[i] << endl; }...

CSE202: Lecture 18The Ohio State University15 logTableError2.cpp... #include... int n(0); cout << "Enter number of integers: "; cin >> n; vector log_table; // Missing (n) for (int i = 0; i < n; i++) { log_table[i] = log(double(i+1)); } for (int i = 0; i < n; i++) { cout << "log(" << i+1 << ") = " << log_table[i] << endl; }...

CSE202: Lecture 18The Ohio State University16 Adding/Removing Elements

CSE202: Lecture 18The Ohio State University17 Reverse List of Positive Integers Read in input list of positive integers ending in 0; Output list in reverse order.

CSE202: Lecture 18The Ohio State University18 reverse3.cpp... int x; vector list; cout << "Enter list of positive integers (ending in 0): "; cin >> x; while (x > 0) { list.push_back(x); cin >> x; } cout << "Reverse list: "; for (int i = list.size(); i > 0; i--) { cout << list[i-1] << " "; } cout << endl;...

CSE202: Lecture 18The Ohio State University19... int x; vector list; cout << "Enter list of positive integers (ending in 0): "; cin >> x; while (x > 0) { list.push_back(x); cin >> x; } cout << "Reverse list: "; for (int i = list.size(); i > 0; i--) { cout << list[i-1] << " "; } cout << endl;... > reverse3.exe Enter list of positive integers (ending in 0): Reverse list:

CSE202: Lecture 18The Ohio State University20 reverseError.cpp... int x; vector list; cout << "Enter list of positive integers (ending in 0): "; cin >> x; int j = 0; while (x > 0) { list[j] = x; // ERROR. Memory for list[j] is not allocated. cin >> x; j++; } cout << "Reverse list: "; for (int i = list.size(); i > 0; i--) { cout << list[i-1] << " "; } cout << endl;...

CSE202: Lecture 18The Ohio State University21 reverseError.cpp... cout << "Enter list of positive integers (ending in 0): "; cin >> x; int j = 0; while (x > 0) { list[j] = x; // ERROR. Memory for list[j] is not allocated. cin >> x; j++; } cout << "Reverse list: "; for (int i = list.size(); i > 0; i--) { cout << list[i-1] << " "; } cout << endl;... > reverseError.exe Enter list of positive integers (ending in 0): Segmentation fault

CSE202: Lecture 18The Ohio State University22 reverse4.cpp... #include... int main() { int x; vector list; cout << "Enter list of positive integers (ending in 0): "; cin >> x; while (x > 0) { list.push_back(x); // add element x to back of list cin >> x; }...

CSE202: Lecture 18The Ohio State University23 reverse4.cpp (cont)... cout << "Reverse list: "; while (list.size() > 0) { int n = list.size(); x = list[n-1]; cout << x << " "; list.pop_back(); // remove last element from list } cout << endl;...

CSE202: Lecture 18The Ohio State University24 Exercise int main() { vector v; for (int i = 3; i < 12; i++) { v.push_back(2*i); } cout << v[2] << endl; cout << v[3] << endl; cout << v[4] << endl; cout << v.size() << endl; return 0; }

CSE202: Lecture 18The Ohio State University25 vector operations vector list; Some member functions of class vector: list[3] = 5; // access element int x = list[3]; list.size(); // number of elements list.push_back(5); // add element to back list.pop_back(); // remove last element list.clear(); // remove all elements

CSE202: Lecture 18The Ohio State University26 Class vector as a Function Parameter

CSE202: Lecture 18The Ohio State University27 Function findMax2() int findMax2(const int array[], const int array_size) { int array_max(0); if (array_size < 1) { return(0); }; // 1. Error: return 0. array_max = array[0]; // 2. max ← A[0]; for (int i = 1; i < array_size; i++) // 3. for i=1 to size-1 do { if (array[i] > array_max) // 4. if (A[i]>max) then { array_max = array[i]; // 5. max ← A[0]; } // 6. endif } // 7. endfor return(array_max); // 8. return max; }

CSE202: Lecture 18The Ohio State University28 arrayMax3().cpp... // function findMax2() prototype int findMax2(const int array[], const int array_size); int main() // main function { const int SIZE_A(6); int array_A[SIZE_A] = { 5, 3, 1, 7, 3, 5 }; const int SIZE_B(8); int array_B[SIZE_B] = { 2, 6, 9, 0, 6, 4, 5, 1 }; int Amax(0), Bmax(0); Amax = findMax2(array_A, SIZE_A); Bmax = findMax2(array_B, SIZE_B); cout << "Max of array A = " << Amax << endl; cout << "Max of array B = " << Bmax << endl; return 0; }

CSE202: Lecture 18The Ohio State University29 Function findVectorMax() #include... int findVectorMax(const vector & v) { int vmax(0); if (v.size() < 1) { return(0); }; // Error: return 0. int vmax = v[0]; for (int i = 1; i < v.size(); i++) { if (v[i] > vmax) { vmax = v[i]; } return(vmax); }

CSE202: Lecture 18The Ohio State University30 vectorMax1().cpp #include... int findVectorMax(const vector & v);... int x(0), vmax(0); vector list; cout << "Enter list of positive integers (ending in 0): "; cin >> x; while (x > 0) { cin >> x; list.push_back(x); // add element x to back of list }; if (list.size() > 0) { vmax = findVectorMax(list); cout << "Maximum integer = " << vmax << endl; }...

CSE202: Lecture 18The Ohio State University31 vectorMax1().cpp... cout << "Enter list of positive integers (ending in 0): "; cin >> x; while (x > 0) { cin >> x; list.push_back(x); // add element x to back of list }; if (list.size() > 0) { vmax = findMax(list); cout << "Maximum integer = " << vmax << endl; }... > vectorMax1.exe Enter list of positive integers (ending in 0): Maximum integer = 7

CSE202: Lecture 18The Ohio State University32 Function moveMax() #include... void moveMax(int array[], const int size) // Note: size is still const { for (int i = 1; i < size; i++) { if (array[0] < array[i]) { swap(array[0], array[i]); }

CSE202: Lecture 18The Ohio State University33 arrayMax4().cpp // include & namespace statements... // function moveMax() prototype void moveMax(int array[], const int size); int main() // main function { const int SIZE_A(6); int array_A[SIZE_A] = { 5, 3, 1, 7, 3, 5 }; const int SIZE_B(8); int array_B[SIZE_B] = { 2, 6, 9, 0, 6, 4, 5, 1 }; moveMax(array_A, SIZE_A); moveMax(array_B, SIZE_B); cout << "Max of array A = " << array1[0] << endl; cout << "Max of array B = " << array2[0] << endl; return 0; }

CSE202: Lecture 18The Ohio State University34 Function move VectorMax() #include... void moveVectorMax(vector & v) { for (int i = 1; i < v.size(); i++) { if (v[i] > v[0]) { swap(v[i], v[0]); }

CSE202: Lecture 18The Ohio State University35 vectorMax2().cpp #include... void moveVectorMax(vector & v);... int x(0); vector list; cout << "Enter list of positive integers (ending in 0): "; cin >> x; while (x > 0) { cin >> x; list.push_back(x); // add element x to back of list }; if (list.size() > 0) { moveVectorMax(list); cout << "Maximum integer = " << list[0] << endl; }...

CSE202: Lecture 18The Ohio State University36 reverseError2().cpp // function prototypes void reverse(vector v); void print_list(const char label[], const vector v); int main() { vector list; list.push_back(11); list.push_back(12); list.push_back(13); print_list("List: ", list); reverse(list); print_list("Reverse list: ", list); return 0; }

CSE202: Lecture 18The Ohio State University37 reverseError2().cpp // reverse list void reverse(vector v) { int n = v.size(); for (int i = 0; i < n/2; i++) { swap(v[i], v[n-1-i]); } // print list void print_list(const char label[], const vector v) { cout << label; for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; } cout << endl; }

CSE202: Lecture 18The Ohio State University38 reverseError2Debug().cpp // reverse list void reverse(vector v) { int n = v.size(); for (int i = 0; i < n/2; i++) { swap(v[i], v[n-1-i]); } print_list("Function reverse: ", v); }

CSE202: Lecture 18The Ohio State University39 reverse5().cpp // function prototypes void reverse(vector & v); void print_list(const char label[], const vector & v); int main() { vector list; list.push_back(11); list.push_back(12); list.push_back(13); print_list("List: ", list); reverse(list); print_list("Reverse list: ", list); return 0; }

CSE202: Lecture 18The Ohio State University40 reverse5().cpp // reverse list void reverse(vector & v) { int n = v.size(); for (int i = 0; i < n/2; i++) { swap(v[i], v[n-1-i]); } // print list void print_list(const char label[], const vector & v) { cout << label; for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; } cout << endl; }

CSE202: Lecture 18The Ohio State University41 Pass by Reference Class vector should always be passed by reference; Use const to indicate a vector which is not going to be modified.

CSE202: Lecture 18The Ohio State University42 Function sort The standard template library sort function will sort the elements of a vector in increasing order; #include // sort from the beginning to the end of the list sort(list.begin(), list.end());

CSE202: Lecture 18The Ohio State University43 sortInt().cpp #include... int main() { int x; vector list; cout << "Enter list of positive integers (ending in 0): "; cin >> x; while (x > 0) { cin >> x; list.push_back(x); // add element x to back of list } sort(list.begin(), list.end()); for (int i = 0; i < list.size(); i++) { cout << list[i] << " "; } cout << endl;...

CSE202: Lecture 18The Ohio State University44 vectorMax3().cpp #include... int main() { int x; vector list; cout << "Enter list of positive integers (ending in 0): "; cin >> x; while (x > 0) { cin >> x; list.push_back(x); // add element x to back of list } sort(list.begin(), list.end()); if (list.size() > 0) { int k = list.size()-1; cout << "Maximum integer = " << list[k] << endl; }...

CSE202: Lecture 18The Ohio State University45 sortString().cpp #include... int main() { string s; vector list; cout << "Enter list of strings (ending with the string \".\"): "; cin >> s; while (s != ".") { cin >> s; list.push_back(s); // add element s to back of list } sort(list.begin(), list.end()); for (int i = 0; i < list.size(); i++) { cout << list[i] << " "; } cout << endl;...

Warning Do not confuse C++ vectors with vectors in mathematics/geometry; C++ vectors store information in a 1- dimensional array; A geometric vector is a geometric object which has both length and direction: CSE202: Lecture 18The Ohio State University46

CSE202: Lecture 18The Ohio State University47 So, Why Use Arrays at All?! Overhead –Vectors use more space and (sometimes) take more time than arrays. When should arrays be used over vectors? –When the array has fixed length. –When the dataset does not need to be contracted or expanded. –When the array is 2 (or 3 or 4) dimensional –When speed is an issue. Note: –C++ vectors are implemented using C arrays.