Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Similar documents
Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

Chapter 9. Pointers and Dynamic Arrays

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

Dynamic Arrays Makefiles and Mul3ple File Compiles

In this chapter, you will learn about: Pointers. Dynamic Arrays. Introduction Computer Science 1 CS 23021

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

Pointers and Dynamic Arrays

Arrays 2 CS 16: Solving Problems with Computers I Lecture #12

More on Strings in C++ Arrays CS 16: Solving Problems with Computers I Lecture #11

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Copyright 2003 Pearson Education, Inc. Slide 1

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

What have we learned about when we learned about function parameters? 1-1

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

In this chapter, you will learn about: An Array Type for Strings. The Standard string Class. Vectors. Introduction Computer Science 1 CS 23021

Numerical Conversions Intro to Strings in C/C++ CS 16: Solving Problems with Computers I Lecture #8

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Pre- Defined Func-ons in C++ Review for Midterm #1

Func%ons in C++ Part 2 CS 16: Solving Problems with Computers I Lecture #5

Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

Sixth lecture; classes, objects, reference operator.

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Lecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1

Programming in C/C Lecture 2

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Introduc)on to Arrays in C++ Review for Midterm #2 CS 16: Solving Problems with Computers I Lecture #12

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Homework #3 CS2255 Fall 2012

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Call- by- Reference Func0ons Procedural Abstrac0ons Numerical Conversions CS 16: Solving Problems with Computers I Lecture #9

File I/O and String Manipula3ons CS 16: Solving Problems with Computers I Lecture #11

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

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Exam 3 Chapters 7 & 9

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

File I/O CS 16: Solving Problems with Computers I Lecture #9

What is an algorithm?

Lecture 2: Memory in C

Pointers, Dynamic Data, and Reference Types

CS2255 HOMEWORK #1 Fall 2012

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

Agenda. Address vs. Value Consider memory to be a single huge array. Review. Pointer Syntax. Pointers 9/9/12

BLM2031 Structured Programming. Zeyneb KURT

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

CS 101: Computer Programming and Utilization

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

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

Pointers II. Class 31

More on File I/O Strings in C++ CS 16: Solving Problems with Computers I Lecture #10

Vector and Free Store (Vectors and Arrays)

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Strings in Python: Cipher Applications CS 8: Introduction to Computer Science Lecture #7

(More) Fun with Pointers and Linked Lists! CS 16: Solving Problems with Computers I Lecture #17

Software Design and Analysis for Engineers

Templates and Vectors

Structures and Classes CS 16: Solving Problems with Computers I Lecture #15

Pointers and Memory 1

Object-Oriented Principles and Practice / C++

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Fundamentals of Structured Programming

Input And Output of C++

Strings in Python: Cipher Applications CS 8: Introduction to Computer Science, Winter 2018 Lecture #9

CS242 COMPUTER PROGRAMMING

Getting started with C++ (Part 2)

CS 101: Computer Programming and Utilization

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Computer Programming

CIS 190: C/C++ Programming. Lecture 2 Pointers and More

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

File I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12

MIPS Instruc,ons CS 64: Computer Organiza,on and Design Logic Lecture #8

Patterns: Working with Arrays

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation

Instructor: Randy H. Katz hap://inst.eecs.berkeley.edu/~cs61c/fa13. Fall Lecture #7. Warehouse Scale Computer

CMSC202 Computer Science II for Majors

Data, memory. Pointers and Dynamic Variables. Example. Pointers Variables (or Pointers) Fall 2018, CS2

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2

The vector Class and Memory Management Chapter 17. Bjarne Stroustrup Lawrence "Pete" Petersen Walter Daugherity Fall 2007

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

Transcription:

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13 Ziad Matni Dept. of Computer Science, UCSB

Announcements Midterm grades will be available on Tuesday, 11/21 If you *need* to know it before, talk to me ager class Your Lab #7 is due on Monday, 11/20 You have lab on Monday, 11/20 (Lab #8 given) We have class on Tuesday, 11/21 We DO NOT have class on Thursday, 11/23 (Happy Thanksgiving!) New Lab #8 is due Monday, 11/27 (ager the break) New Homework #8 is due Tuesday, 11/28 (ager the break) 11/16/17 Matni, CS16, Fa17 2

Quick Note About Strings and Integers If str is a string type var and is 47 and num is an int type var and is 47 stoi(str) = 47 stoi = string- to- int, found in <string> to_string(int) = 47 converts ints and doubles, found in <string> Other cool conversion func_ons: stod(str) = 47.0 string- to- double 11/16/17 Matni, CS16, Fa17 3

Quick Note About getline You can customize what character a getline stops gebng info You can define the character delimiter By default, that s a newline char Example: getline(cin, VariableX, m ) //stops at the char m If the standard input is Hello, I must be going, then VariableX will be Hello, I 11/16/17 Matni, CS16, Fa17 4

Vectors Vectors are a C++ data structure They are like arrays that can change size as your program runs You have less to worry about with vectors re: size changes and mem alloca_ons But vectors consume more memory in exchange for being dynamic and flexible 11/16/17 Matni, CS16, Fa17 5

Vectors Vectors, like arrays, have a base type To declare an empty vector with base type int: vector<int> v; <int> iden_fies vector as a template class You can use any base type in a template class: vector<double> v; vector<string> v; etc 11/16/17 Matni, CS16, Fa17 6

Accessing vector Elements Vectors elements are indexed star_ng with 0 [ ]'s are used to read or change the value of an item: v[i] = 42; cout << v[i]; But [ ]'s cannot be used to ini_alize a vector element 11/16/17 Matni, CS16, Fa17 7

Ini_alizing vector Elements Elements are added to a vector using the vector member func9on push_back( ) push_back adds an element in the next available posi_on Example: vector<double> sample; sample.push_back(0.0); sample.push_back(1.1); sample.push_back(2.2); 11/16/17 Matni, CS16, Fa17 8

The size of a vector The member func_on size( ) returns the number of elements in a vector (don t you wish you had that with arrays!?!) Example: To print each element of a vector: vector<double> sample; sample.push_back(0.0); sample.push_back(1.1); sample.push_back(2.2); for (int i= 0; i < sample.size( ); i++) cout << sample[i] << endl; 11/16/17 Matni, CS16, Fa17 9

The Type unsigned int The vector class member func_on size returns an unsigned int type of value Unsigned int's are non- nega_ve integers Some compilers will give a warning if the previous for- loop is not changed to: for (unsigned int i= 0; i < sample.size( ); i++) cout << sample[i] << endl; However, g++ with std=c++11 seems ok with plain old int 11/16/17 Matni, CS16, Fa17 10

Alternate vector Ini_aliza_on A vector constructor exists that takes an integer argument and ini_alizes that number of elements A constructor is a part of a class that is usually used for ini_aliza_on purposes Example: vector<int> v(10); ini_alizes the first 10 elements to 0 v.size( ) would then return 10 [ ]'s can now be used to assign elements 0 through 9 push_back is used to assign elements greater than 9 11/16/17 Matni, CS16, Fa17 11

The vector Library To use the vector class You have to include the vector library #include <vector> Vector names are placed in the standard namespace so the usual using direc_ve is needed: using namespace std; 11/16/17 Matni, CS16, Fa17 12

See textbook, pg. 493 13

Defining vector Elements Beyond Vector Size Asemp_ng to use [ ] to set a value beyond the size of a vector may not generate an error, but it is not correct to do! Example: assume integer vector v has 3 elements in it Performing an assignment like v[5] = 4 isn t the correct thing to do INSTEAD you should use push_back( ) enough _mes to get to element 5 first before making changes Even though you may not get an error, you have messed around with memory alloca_ons and the program will probably misbehave in other ways 11/16/17 Matni, CS16, Fa17 14

vector Efficiency A vector's capacity is the number of spaces in memory that are put aside for vector elements size( ) is the number of elements ini#alized capacity( ) is the number of elements that are put aside (automa9cally reserved) When a vector runs out of space, the capacity is automa9cally increased! A common scheme by the compiler is to double the size of a vector 11/16/17 Matni, CS16, Fa17 15

Controlling vector Capacity When efficiency is an issue and you want to control memory use (i.e. and not rely on the compiler) Use member func_on reserve( ) to increase the capacity of a vector Example: v.reserve(32); // at least 32 elements v.reserve(v.size( ) + 10); // at least 10 more resize( ) can be used to shrink a vector Example: v.resize(24); //elements beyond 24 are lost 11/16/17 Matni, CS16, Fa17 16

INTRO TO POINTERS Sec9on 9.1 in book 11/16/17 Matni, CS16, Fa17 17

Memory Addresses Consider the integer variable num that holds the value 42 1 byte Address 001D 001E Data num 001F 42 num is assigned a place in memory. 0020 0021 In this example the address of that place in memory is 0x001F Generally, memory addresses use hexadecimals (just not only 4 of them ) The 0x at the start is just to indicate the number is a hex 0022 11/16/17 Matni, CS16, Fa17 18

Memory Addresses The address of a variable can be obtained by pubng the ampersand character (&) before the variable name. & is called the address- of operator 1 byte num Address Data 001D 001E 001F 42 0020 Example: 0022 int num_add = &num; will result in num_add to hold the value 001F (but expressed in decimal) 0021 11/16/17 Matni, CS16, Fa17 19

Memory Address Recall: num = 42 and num_add = &num = 0x001F Now, let s make bar = num Another variable, bar, now is assigned the same value that s in num (42) The variable bar will be assigned an address Let s say, that address is 0x3A77 Keep in mind, by default, we have no control over address assignments The variable that stores the address of another variable (like num_add) is called a pointer. 11/16/17 Matni, CS16, Fa17 20

Dereference Operator (*) Pointers point to the variable whose address they store Pointers can access the variable they point to directly This access is done by preceding the pointer name with the dereference operator (*) The operator itself can be read as value pointed to by So, while num_add = 0x001F, *num_add = 42 11/16/17 Matni, CS16, Fa17 21

Pointers A pointer is the memory address of a variable When a variable is used as a call- by- reference argument, it s the actual address in memory that is passed 11/16/17 Matni, CS16, Fa17 22

Pointers Tell Us (or the Compiler) Where To Find A Variable Pointers "point" to a variable by telling where the variable is located 11/16/17 Matni, CS16, Fa17 23

Declaring Pointers Pointer variables must be declared to have a pointer type Example: To declare a pointer variable p that can "point" to a variable of type double: double *p; The asterisk (*) iden_fies p as a pointer variable 11/16/17 Matni, CS16, Fa17 24

Mul_ple Pointer Declara_ons To declare mul_ple pointers in a statement, use the asterisk before each pointer variable Example: int *p1, *p2, v1, v2; p1 and p2 point to variables of type int v1 and v2 are variables of type int 11/16/17 Matni, CS16, Fa17 25

The address- of Operator The & operator can be used to determine the address of a variable which can be assigned to a pointer variable Example: p1 = &v1; p1 is now a pointer to v1 v1 can be called the variable pointed to by p1 11/16/17 Matni, CS16, Fa17 26

A Pointer Example v1 = 0; p1 = &v1; *p1 = 42; cout << v1 << endl; cout << *p1 << endl; v1 and *p1 now refer to the same variable v1 p1 v1 p1 output: 42 42 0 42 11/16/17 Matni, CS16, Fa17 27

Pointer Assignment The assignment operator = is used to assign the value of one pointer to another Example: If p1 s_ll points to v1 (previous slide) v1 p2 = p1 then the statement p2 = p1; 42 causes *p2, *p1, and v1 all to name the same variable 11/16/17 Matni, CS16, Fa17 28

Cau_on! Pointer Assignments Some care is required making assignments to pointer variables Assuming p1 and p3 are pointers p1 = p3; // changes the location that p1 "points" to *p1 = *p3; // changes the value at the location that // p1 "points" to 11/16/17 Matni, CS16, Fa17 29

Uses of the Assignment Operator on Pointers 11/16/17 Matni, CS16, Fa17 30

Uses of the Assignment Operator on Pointers 11/16/17 Matni, CS16, Fa17 31

The new Operator Using pointers, variables can be manipulated even if there is no iden_fier for them To create a pointer to a new nameless variable of type int: p1 = new int; The new variable is referred to as *p1 *p1 can be used anyplace an integer variable can Example: cin >> *p1; *p1 = *p1 + 7; 11/16/17 Matni, CS16, Fa17 32

Dynamic Variables Variables created using the new operator are called dynamic variables Dynamic variables are created and destroyed while the program is running We don t have to bother with naming them, just their pointers 11/16/17 Matni, CS16, Fa17 33

p1 p2 42

88 p1 p2 42 53

88 p1 p2 42 53

Basic Memory Management: The Heap An area of memory called the freestore or the heap is reserved for dynamic variables New dynamic variables use memory in the heap If all of the heap is used, calls to new will fail So you need to manage your unused dynamic variables Un- needed memory can be recycled When variables are no longer needed, they can be deleted and the memory they used is returned to the heap 11/16/17 Matni, CS16, Fa17 37

The delete Operator When dynamic variables are no longer needed, delete them to return memory to the heap Example: delete p; The value of p is now undefined and the memory used by the variable that p pointed to is back in the heap 11/16/17 Matni, CS16, Fa17 38

Dangling Pointers Using delete on a pointer variable destroys the dynamic variable pointed to (frees up memory too!) If another pointer variable was poin_ng to the dynamic variable, that variable is also now undefined Undefined pointer variables are called dangling pointers Dereferencing a dangling pointer (*p) is usually disastrous 11/16/17 Matni, CS16, Fa17 39

Automa_c Variables As you know: variables declared in a func_on are created by C++ and then destroyed when the func_on ends These are called automa#c variables because their crea_on and destruc_on is controlled automa_cally However, the programmer must manually control crea_on and destruc_on of pointer variables with operators new and delete 11/16/17 Matni, CS16, Fa17 40

Type Defini_ons A name can be assigned to a type defini_on, then used to declare variables The keyword typedef is used to define new type names Syntax: typedef Known_Type_Defini9on New_Type_Name; where, Known_Type_Defini9on can be any type 11/16/17 Matni, CS16, Fa17 41

Defining Pointer Types To help avoid mistakes using pointers, define a pointer type name Example: typedef int* IntPtr; Defines a new type, IntPtr, for pointer variables containing pointers to int variables IntPtr p; is now equivalent to saying: int *p; 11/16/17 Matni, CS16, Fa17 42

Mul_ple Declara_ons Again Using our new pointer type defined as typedef int* IntPtr; Helps prevent errors in pointer declara_on For example, if you want to declare 2 pointers, instead of this: int *p1, p2; // Careful! Only p1 is a pointer variable! do this: IntPtr p1; int p2; // p1 and p2 are both pointer variables 11/16/17 Matni, CS16, Fa17 43

Pointer Reference Parameters A second advantage in using typedef to define a pointer type is seen in parameter lists, like Example: void sample_function(intptr& pointer_var); is less confusing than: void sample_function(int*& pointer_var); 11/16/17 Matni, CS16, Fa17 44

q HW 8 due Tue. 11/28 q Lab 8 due Mon. 11/27 YOUR TO- DOs q Visit Prof s and TAs office hours if you need help! q Rinse, Wash, Repeat 11/16/17 Matni, CS16, Fa17 45

11/16/17 Matni, CS16, Fa17 46