Chapter 6 Vectors and arrays: Arrays: Run the following code. Anything unusual? #include using namespace std; #define N 10 #define M 11 int main() { int.

Slides:



Advertisements
Similar presentations
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Advertisements

Chapter 14 Operator Overloading: What does + mean? Consider the code below. Note the multiple uses of “+”. #include using namespace std; int main() { int.
Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
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.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Chapter 10.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
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.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Review of C++ Programming Part II Sheng-Fang Huang.
 CS105 C++ Lecture 2 Arrays. Parameter passing  2 types  Pass-by-value  Pass-by-reference 2.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
Chapter 8 Arrays and Strings
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Lists. Container Classes Many applications in Computer Science require the storage of information for collections of entities e.g. a student registration.
Chapter 1 Arrays, Pointers, and Structures Saurav Karmakar Spring 2007.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Lists II. List ADT When using an array-based implementation of the List ADT we encounter two problems; 1. Overflow 2. Wasted Space These limitations are.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
1 Chapter 7 Arrays. 2 Topics 7.1 Arrays Hold Multiple Values 7.2 Accessing Array Elements 7.3 No Bounds Checking in C Array Initialization 7.5 Processing.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
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.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
Pointers and Arrays Dynamic Variables and Arrays.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Pointers and Dynamic Arrays
EGR 2261 Unit 9 One-dimensional Arrays
Computer Programming BCT 1113
Dynamic Memory CSCE 121 J. Michael Moore.
CSCE 210 Data Structures and Algorithms
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
7 Arrays.
Presentation transcript:

Chapter 6 Vectors and arrays: Arrays: Run the following code. Anything unusual? #include using namespace std; #define N 10 #define M 11 int main() { int x = 10; int a[N]; cout << " x is equal to " << x << endl; for (int i=1; i<=M; i++) a[i]=i*i; for (int i=1; i<=N; i++) cout << i << " " << a[i] << endl; cout << " x is equal to " << x << endl; cin.get(); }

Vector: collection of data items of the same type (much like an array) General format: vector name(initial size) Example declarations: vector scores(50); vector staff(20); Need: #include initial size can be 0 to start with an empty vector.

Access vector elements just like with arrays variable_name[i]. Legal subscripts are 0 through initial_size-1. If v is the vector variable then v.size() represents the number of elements in the vector. Thus, v.size()-1 is the largest legal subscript.

v.push_back(value) increases the vector size by one and puts the value in the new spot. v.pop_back() decreases the vector size by one, losing the value in the last position. Although convenient, it can be inefficient!

Run the following code in the tempdemo project. vector x(3); for (vector ::size_type i=0; i < x.size(); i++) cin >> x[i]; for (vector ::size_type i=0; i<x.size(); i++) cout << x[i] << " "; cout << endl; x.push_back(99); x.push_back(999); for (vector ::size_type i=0; i<x.size(); i++) cout << x[i] << " "; cout << endl; x.pop_back(); for (vector ::size_type i=0; i<x.size(); i++) cout << x[i] << " "; cout << endl;

If you go beyond the vector limits the program MAY NOT generate an out of bounds exception!! This can be dangerous and cause unpredictable results. Try the code on the next slide and see what happens Must take care in writing programs. An exception is thrown in VB.NET If the cpp file is copied to Linux and compiled using g++, then no exception is thrown at the point where the illegal subscript is referenced but a segment fault error occurs.

vector x(3); vector y(3); for (vector ::size_type i=0; i < y.size(); i++) cin >> y[i]; for (vector ::size_type i=0; i <= x.size(); i++) cin >> x[i]; for (vector ::size_type i=0; i< x.size(); i++) cout << x[i] << " "; cout << endl; for (vector ::size_type i=0; i< y.size(); i++) cout << y[i] << " "; cin.get();

See p. 274 for a well publicized problem (Internet worm) related to array overflow.

Seeing vector values in the debugger: Put the vector name in a watch window. Vector values appear but the display does not tell the whole story of what’s going on. The vector state _Myfirst is a pointer to a memory location containing the first element of the vector. There is also _Mylast which indicates the end of the vector.

Put *(v._Myfirst) in the watch window to see the first vector item. *(v._Myfirst+1) locates the next item, *(v._Myfirst+2) the next one, and so on. Use *(v._Mylast-1) to show the last item in the vector.

NOTE: How to declare a vector (vector v(5)) as an item in a struct or class definition!!! Examine the following code and note the error: #include using namespace std; #include class test { public: test(); void put(int i, int x); int get(int i); private: vector v(5); }; int test::get(int i) { return v[i]; } void test::put(int i, int x) { v[i] = x; } test::test() {} int main() { test x; x.put(2,22); int y = x.get(2); exit (0); }

Reasons and solutions follow: The above is more than just a declaration of 5 elements. The intent is to call a constructor, passing a parameter of 5 to it. This cannot be done in a declaration. Vectors are not arrays despite the use of [] to access a particular element. Use of [] is allowed because the [] is overloaded (discussed later).

Proper way to set up a vector in a class is to write v(5) in the field initializer list p. 248) of the constructor. i.e. if the class name were C then you’d have C::C(pars) : ….,v(5),… Thus in the above code declare the vector as vector v; and replace the constructor with test::test():v(5){}. Show what happens if only the first change in the previous bullet is done.

Suggestion: Do NOT use notation such as v[i++]. It can be confusing. The string type is a vector of characters. See code snippets starting on page 275 to see how a vector can be passed as a value or reference parameter or how it can be returned via a function name. See note on passing by constant reference (p. 277) to increase performance.

Removing vector elements: If no particular order, overwrite the element to be deleted with the last element and shrink the vector by 1. See logic on p If elements are in order, must shift, then shrink. See logic on p Similar issues for inserting an element (p. 278).

Quality Tip 6.2, Parallel vectors: Example: collection of students, GPAs, majors, and credits. Might use 4 vectors and represent a student by using the ith element in each vector. This is BAD design! Better to set up a student class and create a vector of objects. Authors call parallel vectors evil. They are!

Arrays: like vectors but can not be resized. Array size (capacity) specified at compile time. Programmer must specify the size. Also called static arrays. Programmer must estimate how many elements to allocate to the array. Inefficiency if the array is bigger than you really need. Problems if it is smaller. Each array must have a companion variable, a variable indicating the number of elements actually stored in the array.

This is different than the array capacity. HOWEVER, arrays are more efficient than vectors when it comes to accessing the elements. Each has its own advantages and disadvantages.

Character arrays. Used before string class became available. May see this in CS370. array of characters with ‘\0’ at the end. Could initialize by using char greeting[6]=”Hello”. Need 6 positions to account for the NULL terminator. C provides a strlen() function that return the number of characters in a string. i.e. strlen(greeting) returns 5.

See example code on page 287. Also have functions: strcat, strncat, strcpy, strncpy. May see more of this in CS370. must sometimes be used for backward compatibility.

Examples: char year[]="1999";int y;y=atoi(year); //This is OK!! string year="1999";int y;y=atoi(year); //This is NOT OK!! //Need to use y=atoi(year.c_str());

There is a problem with trying to return an array via a function name. It will work for a vector but not an array. Reason is related to the fact that an array is NOT a class and that "=" is NOT an overloaded operator for an array. Array parameters are always passed by reference!! An array parameter must always be accompanied by its companion variable (its size)

Two dimensional arrays: type var[NROWS] [NCOLS]. Access a row using notation var [i] [j]. Each of i and j must be >=0 and <= the limit. When passing as a parameter, must specify the number of columns as a constant in the parameter declaration. Number of rows is not required. Reason is that arrays are stored by placing rows in consecutive memory locations. Need only the row length (# columns) to resolve a memory reference.

Later you’ll learn that char x[10] and char* x are similar. First is static allocation; second allows memory allocation to be done dynamically. In the latter case, this allows the programmer to design the ability to expand the array into the software. In turn, this allows the programmer to get around some of the array’s disadvantages while preserving its advantages. However, it is more work for the programmer.

The banking program demo contains objects with both arrays and vectors.