Patterns: Working with Arrays
|
|
- Lindsay Drusilla Day
- 5 years ago
- Views:
Transcription
1 Steven Zeil October 14, 2013
2 Outline 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates 4 Vectors 5 Multi-Dimension Arrays Arrays of Arrays
3 Static & Dynamic Allocation Outline I 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates 4 Vectors 5 Multi-Dimension Arrays Arrays of Arrays
4 Static & Dynamic Allocation Static Allocation Static Allocation const i n t MaxItems = 1 00; // Names o f i t e m s s t d : : s t r i n g itemnames [ MaxItems ] ; Simple Best suited to situations where we know the number of items at compile time s t r i n g monthnames [ 1 2 ] ;
5 Static & Dynamic Allocation Static Allocation How Many Elements Do We Need? If we don t know how many elements we really need, we need to guess Too few, and the program crashes Too many, and we waste space (and maybe time)
6 Static & Dynamic Allocation Dynamic Allocation Dynamic Allocation Use pointer to array Allocated on heap Needs to be deleted afterwards
7 Static & Dynamic Allocation Dynamic Allocation Example: bidders.h extern i n t n B i d d e r s ; extern Bidder b i d d e r s ; void r e a d B i d d e r s ( s t d : : i s t r e a m& i n ) ;
8 Static & Dynamic Allocation Dynamic Allocation Example: bidders.cpp bidders.cpp ❶ Here we read the desired size of the arrays from the input ❷ Here we use that value to actually allocate arrays of the desired size ❸ Once that is done, we can access the arrays in the usual manner using the [ ].
9 Static & Dynamic Allocation Dynamic Allocation Dynamic Array Declarations are Confusing extern Bidder b i d d e r s ; We can t tell by looking at this declaration whether it is intended to point to a single bidder, or an array of bidders Need to rely on documentation
10 Static & Dynamic Allocation Dynamic Allocation Why Are Arrays Different? Because arrays are "really" pointers... array1 = array2; does not copy the array When arrays are passed to functions, we are actually passing a pointer passing arrays is fast and efficient changes to the array can be seen by the caller i n t x ; i n t a r r [ ] ; void. foo ( i n t i, i n t a ) ; foo ( x,. a ) ; void foo ( i n t i, i n t a ) { i = i + 1 ; // does not a f f e c t x a [ 0 ] = i ; // does a f f e c t a r r }
11 Partially Filled Arrays Outline I 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates 4 Vectors 5 Multi-Dimension Arrays Arrays of Arrays
12 Partially Filled Arrays Partially Filled Arrays To work with a partially filled array, we generally need to have access to the array itself an integer counter indicating how many elements are currently in the array the size or length of the list an integer counter indicating the maximum nmber of elements we can have without overflowing the array the capacity of the list
13 Partially Filled Arrays Adding Elements Adding Elements Variations include adding to the end adding in the middle adding in order
14 Partially Filled Arrays Adding Elements Add to the end void addtoend ( s t d : : s t r i n g a r r a y, i n t& s i z e, s t d : : s t r i n g { a r r a y [ s i z e ] = v a l u e ; ++s i z e ; } Assumes that we have a separate integer indicating how many elements are in the array and that the "true" size of the array is at least one larger than the current value of that counter
15 Partially Filled Arrays Adding Elements Add to the middle addelement (array, size, index, value) Adds value into array[index], shifting all elements already in positions index..size-1 up one, to make room. Increments the size variable If we have this and we do addelement ( a r r a y, 3, 1, " Smith " ) ; we should get this.
16 Partially Filled Arrays Adding Elements Add to the middle: implementation addelement.cpp You can try out the addtoend and addelement functions here. Try them out with different inputs until you understand how they work.
17 Partially Filled Arrays Adding Elements Add in order int addinorder (array, size, value) Assume the elements of the array are already in order Find the position where value could be added to keep everything in order, and insert it there. Return the position where it was inserted If we have this and we do addinorder ( a r r a y, 3, " C l a r k e " ) ; we should get this
18 Partially Filled Arrays Adding Elements Add in order implementation This works: i n t addinorder ( s t d : : s t r i n g a r r a y, i n t& s i z e, s t d : : s t r i n g v a l u e ) { // Find where to i n s e r t i n t pos = 0 ; while ( pos < s i z e && v a l u e > a r r a y [ pos ] ) ++pos ; addelement ( a r r a y, s i z e, pos, v a l u e ) ; return pos ; }
19 Partially Filled Arrays Adding Elements Add in order (streamlined) This is a bit faster: i n t addinorder ( ( s t d : : s t r i n g a r r a y, i n t& s i z e, s t d : : s t r i n g v a l u e ) { // Make room f o r the i n s e r t i o n i n t tobemoved = s i z e 1 ; while ( tobemoved >= 0 && v a l u e < a r r a y [ tobemoved ] ) { a r r a y [ tobemoved+1] = a r r a y [ tobemoved ] ; tobemoved ; } // I n s e r t the new v a l u e a r r a y [ tobemoved+1] = v a l u e ; ++s i z e ; return tobemoved +1; } Try This: You can try out the two addinorder functions here.
20 Partially Filled Arrays Searching for Elements Sequential Search Search an array for a given value, returning the index where found or -1 if not found. seqsearch.cpp How many elements does this visit in the worst case? How many elements does this visit on average? if searchitem is in the array? if searchitem is not in the array?
21 Partially Filled Arrays Searching for Elements Sequential Search 2 Search an array for a given value, returning the index where found or -1 if not found. i n t s e q S e a r c h ( const i n t l i s t [ ], i n t l i s t L e n g t h, i n t s e a r c { i n t l o c ; f o r ( l o c = 0 ; l o c < l i s t L e n g t h ; l o c++) i f ( l i s t [ l o c ] == s e a r c h I t e m ) return l o c ; } return 1;
22 Partially Filled Arrays Searching for Elements Sequential Search (Ordered Data) Search an array for a given value, returning the index where found or -1 if not found. If data is in order, we can stop early as soon as list[loc] > searchitem
23 Partially Filled Arrays Searching for Elements seqorderedsearch i n t s e qorderedsearch ( const i n t l i s t [ ], i n t l i s t L e n g t h, i n { i n t l o c = 0 ; } while ( l o c < l i s t L e n g t h && l i s t [ l o c ] < s e a r c h I t e m ) { ++l o c ; } i f ( l o c < l i s t L e n g t h && l i s t [ l o c ] == s e a r c h I t e m ) return l o c ; e l s e return 1; How many elements does this visit in the worst case? How many elements does this visit on average? if searchitem is in the array? if searchitem is not in the array?
24 Partially Filled Arrays Removing Elements Removing Elements removeelement (std::string* array, int& size; int index) void removeelement ( s t d : : s t r i n g a r r a y, i n t& s i z e, i n t i n d e x ) { i n t tobemoved = i n d e x + 1 ; while ( tobemoved < s i z e ) { a r r a y [ tobemoved 1] = a r r a y [ tobemoved ] ; ++tobemoved ; } s i z e ; } Try This: You can try out the removeelement function here.
25 Arrays and Templates Outline I 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates 4 Vectors 5 Multi-Dimension Arrays Arrays of Arrays
26 Arrays and Templates arrayutils - first draft The functions we have developed in this section can be used in many different programs, so it might be useful to collect them into an "Array Utilities" module. Header: arrayutils0.h Compilation unit: arrayutils0.cpp Test driver: testarrayutils0.cpp Question: The main function will not compile. Why?
27 Arrays and Templates Overloading One solution is to provide different versions of each function for each kind of array: // Search an o r d e r e d a r r a y f o r a g i v e n value, r e t u r n i n g // found or 1 i f not found. i n t s e qorderedsearch ( const i n t l i s t [ ], i n t l i s t L e n g t h, i n i n t s e qorderedsearch ( const char l i s t [ ], i n t l i s t L e n g t h, i n t s e qorderedsearch ( const double l i s t [ ], i n t l i s t L e n g t h i n t s e qorderedsearch ( const f l o a t l i s t [ ], i n t l i s t L e n g t h, i n t s e qorderedsearch ( const s t d : : s t r i n g l i s t [ ], i n t l i s t L e with nearly identical function bodies for each one. called overloading the function name Tedious Not possible to cover all possible data types
28 Arrays and Templates Function Templates A function template is a pattern for an infinite number of possible functions. Contains special symbols called template parameters that function like blank spaces in a form Symbols can be replaced to "fill out" the form Called instantiating the template
29 Arrays and Templates A Simple Template swap.cpp The template header announces that is a template. Without this, it would look like an ordinary function The header lists the template parameters for this pattern. These will be replaced when the template is used (instantiated). Can have more than one (comma-separated) Each preceded by the word typename or class Each template parameter must appear as a type somewhere in the function s parameter list The swap template is declared in the std library header <algorithm>
30 Arrays and Templates Using A Function Template Import it from the appropriate header (if not declared locally) Call it with the desired parameters Compiler figures out what substitutions to make #i n c l u de <a l g o r i t h m > using. namespace s t d ; s t r i n g a = " abc " ; s t r i n g b = " bcde " ; swap ( a, b ) ; // c o m p i l e r r e p l a c e s "T" by " s t r i n g " i n t i = 0 ; i n t j = 2 ; swap ( i, j ) ; // c o m p i l e r r e p l a c e s "T" by " i n t "
31 Arrays and Templates Some Other std Function Templates min(x,y) returns the smaller of two values max(x,y) returns the larger of two values fill_n(array, N, value) fills array[0]..array[n-1] with value
32 Arrays and Templates Building a Library of Array Templates Second try, using templates: Header: arrayutils.h Test driver: testarrayutils.cpp
33 Arrays and Templates Function Templates Are Not Functions Is it a problem that we have the bodies in a.h file?
34 Arrays and Templates Function Templates Are Not Functions Is it a problem that we have the bodies in a.h file? No, because function templates are not functions, they are patterns for functions.
35 Arrays and Templates Patterns versus Instances In the same way that This is not an admission application. But this is an admission application. These are not functions. The code generated by the compiler in response to our calls are the functions.
36 Vectors Outline I 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates 4 Vectors 5 Multi-Dimension Arrays Arrays of Arrays
37 Vectors Keeping Information Together One criticism of functions like void addtoend ( s t d : : s t r i n g a r r a y, i n t& s i z e, s t d : : s t r i n g v a l u e ) ; i n t addinorder ( s t d : : s t r i n g a r r a y, i n t& s i z e, s t d : : s t r i n g v a l u e ) ; is that they separate the array, the size, and the capacity Easy for programmers to lose track of which integer counter applies to which array Complicates functions to pass this information separately.
38 Vectors Wrapping arrays within structs One solution: use a struct to gather the related elements together: /// A c o l l e c t i o n o f i t e m s s t r u c t ItemSequence { s t a t i c const i n t c a p a c i t y = 500; i n t s i z e ; Item data [ c a p a c i t y ] ; } ;
39 Vectors A Better Version Using dynamic allocation, we can be more flexible about the capacity: s t r u c t ItemSequence { i n t c a p a c i t y ; i n t s i z e ; Item data ; } ; ItemSequence ( i n t cap ) ; void addtoend ( Item item ) ;
40 Vectors Implementing the Sequence ItemSequence : : ItemSequence ( i n t cap ) : c a p a c i t y ( cap ), s i z e ( 0 ) { data = new Item [ c a p a c i t y ] ; } void ItemSequence : : addtoend ( Item item ) { i f ( s i z e < c a p a c i t y ) { data [ s i z e ] = item ; ++s i z e ; } e l s e c e r r << " E r r o r : ItemSequence i s f u l l " << e n d l ; }
41 Vectors Vectors the Un-Array The vector is an array-like structure provided in the std header <vector>. Think of it as an array that can grow at the high end actually another kind of template, a class template
42 Vectors Declaring Vectors s t d : : v e c t o r <int > v i ; // a v e c t o r o f 0 i n t s s t d : : v e c t o r <s t d : : s t r i n g > vs ( 1 0 ) ; // a v e c t o r o f 10 // empty s t r i n g s s t d : : v e c t o r <f l o a t > v f ( 5, 1. 0 ) ; // a v e c t o r o f 5 // f l o a t s, a l l 1. 0 The type name inside the < > describes the elements contained inside the vector
43 Vectors Accessing Elements in a Vector Use the [ ] just as with an array: v e c t o r <int > v ( 1 0 ) ; f o r ( i n t i = 0 ; i < 1 0 ; ++i ) { i n t j ; c i n >> j ; v [ i ] = j + 1 ; cout << v [ i ] << e n d l ; }
44 Vectors Size of a Vector void foo (vector<int>& v) { } for (int i = 0; i < { } int j; cin >> j; v[i] = j + 1; cout << v[i] << endl; v.size() ; ++i) Vectors remember their own size Accessed via size() With vectors, we do not over-allocate extra spaces in the vector and use a separate counter
45 Vectors Adding to a Vector Adding to the end: This is how we "grow" a vector. v. push_back ( x ) ;
46 Vectors Adding to the Middle template <c l a s s Vector, c l a s s T> void addelement ( Vector& v, i n t index, T v a l u e ) { // Make room f o r the i n s e r t i o n i n t tobemoved = v. s i z e ( ) 1 ; v. push_back ( v a l u e ) ; // expand v e c t o r by 1 s l o t while ( tobemoved >= i n d e x ) { v [ tobemoved+1] = v [ tobemoved ] ; tobemoved ; } // I n s e r t the new v a l u e v [ i n d e x ] = v a l u e ; }
47 Vectors Adding to the Middle: v2 Actually, vector s provide a built-in operation for inserting into the middle: s t r i n g a ; // a r r a y o f s t r i n g s v e c t o r <s t r i n g > v ; i n t k, n ;. v. i n s e r t ( v. b e g i n ()+k, " H e l l o " ) ; addelement ( a, n, k, " H e l l o " ) ; The last two statements do the same thing. But insert is a built-in member function of vectors The way of specifying the position is a bit odd. v.begin() is a pointer to the start of the vector Like a is a pointer to the start of the array v.begin() + k is a pointer to v[k] Like a + k is a pointer to the a[k]
48 Vectors Add in Order to Vector template <c l a s s Vector, c l a s s T> i n t addinorder ( Vector& v, T v a l u e ) { // Make room f o r the i n s e r t i o n i n t tobemoved = v. s i z e ( ) 1 ; v. push_back ( v a l u e ) ; // expand v e c t o r by 1 s l o t while ( tobemoved >= 0 && v a l u e < v [ tobemoved ] ) { v [ tobemoved+1] = v [ tobemoved ] ; tobemoved ; } // I n s e r t the new v a l u e v [ tobemoved+1] = v a l u e ; return tobemoved +1; }
49 Vectors Advantages of Vectors Can grow as necessary Need not worry about pointers, allocation, delete Vectors can copy: v1 = v2;
50 Vectors Disadvantages of Vectors A bit slower than arrays push_back is sometimes very slow Can waste a lot of storage but so can arrays if we have to guess at max Harder to work with in a debugger
51 Multi-Dimension Arrays Outline I 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates 4 Vectors 5 Multi-Dimension Arrays Arrays of Arrays
52 Multi-Dimension Arrays Multi-Dimension Arrays Used in situations where we would arrange data into a table rather than a list. If we know how many rows and columns, Allocate array as i n t a r r a y [ numrows ] [ numcols ] ; Access as array[i][j] 0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2 3,0 3,1 3,2
53 Multi-Dimension Arrays Example test2dimfixed.cpp
54 Multi-Dimension Arrays Arrays of Arrays Arrays of Arrays If we do not know (at compile time) how many rows and columns, Declare array as i n t a r r a y ; Allocate as an array of pointers: a r r a y = new i n t [ numrows ] ; Each row must then be allocated as an array a r r a y [ i ] = new i n t [ numcols ] ; Access as array[i][j] Example: test2dimrowscols.cpp ,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2 3,0 3,1 3,2
55 Multi-Dimension Arrays Arrays of Arrays Linearized Arrays We can map 2-D arrays onto a linear structure i n t i n d e x ( i n t i, j, numcols ) { return j + i numcolss ; } 0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2 3,0 3,1 3,2
56 Multi-Dimension Arrays Arrays of Arrays Linearized Array Code 0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2 3,0 3,1 3,2 Declare array as i n t a r r a y ; Allocate as a 1-D array a r r a y = new i n t [ numrows numcols ] ; Access as array[index(i,j,numcols)]
Operator Overloading
Steven Zeil November 4, 2013 Contents 1 Operators 2 1.1 Operators are Functions...................................................... 2 2 I/O Operators 4 3 Comparison Operators 38 3.1 Equality Operators.........................................................
More informationType Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works
Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.
More informationOperator Overloading
Steven Zeil November 4, 2013 Contents 1 Operators 2 1.1 Operators are Functions.... 2 2 I/O Operators 4 3 Comparison Operators 6 3.1 Equality Operators....... 11 3.2 Less-Than Operators...... 13 1 1 Operators
More informationPointers and References
Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers
More informationDefensive Programming
Steven Zeil July 22, 2013 Contents 1 Common Assumptions 2 2 Documenting Assumptions 2 3 Guarding Assumptions 5 3.1 Guarding Assumptions with Assertions............................... 8 1 Defensive Programming
More informationComputer Science II Lecture 2 Strings, Vectors and Recursion
1 Overview of Lecture 2 Computer Science II Lecture 2 Strings, Vectors and Recursion The following topics will be covered quickly strings vectors as smart arrays Basic recursion Mostly, these are assumed
More information6. Pointers, Structs, and Arrays. March 14 & 15, 2011
March 14 & 15, 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 47 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung
More informationEncapsulation. Contents. Steven Zeil. July 17, Encapsulation Encapsulation in C Classes 4. 3 Hiding Attributes 8
Steven Zeil July 17, 2013 Contents 1 Encapsulation 2 1.1 Encapsulation in C++........................................................ 2 2 Classes 4 3 Hiding Attributes 8 4 Inline Functions 11 4.1 How Functions
More informationConsider the above code. This code compiles and runs, but has an error. Can you tell what the error is?
Discussion 1H Notes (Week 8, May 20) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 Dynamic Allocation of Memory Recall that when you create an array, you must know
More informationLesson 13 - Vectors Dynamic Data Storage
Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts
More informationAlgorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14
Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer Science, UCSB Administra:ve Turn in Homework #12 Homework #13 is due Tuesday Lab
More informationBasic Templates Intro
1 Basic Templates Intro C++ is a strongly typed language - there is strict set of rules on what types that variables can have, and when one type can be used as another type. e.g. conversion rules: my_int
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010
CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)
More informationLinked Lists. Contents. Steven J. Zeil. July 31, Linked Lists: the Basics 4
Steven J. Zeil July 31, 2013 Contents 1 Linked Lists: the Basics 4 1 2 Coding for Linked Lists 8 2.1 Traversing a Linked List............................... 12 2.2 Searching a Linked List................................
More information6. Pointers, Structs, and Arrays. 1. Juli 2011
1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 50 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung
More informationPage. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team
Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10
More informationA brief introduction to C++
A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne
More informationCS93SI Handout 04 Spring 2006 Apr Review Answers
CS93SI Handout 04 Spring 2006 Apr 6 2006 Review Answers I promised answers to these questions, so here they are. I'll probably readdress the most important of these over and over again, so it's not terribly
More informationCopying Data. Contents. Steven J. Zeil. November 13, Destructors 2
Steven J. Zeil November 13, 2013 Contents 1 Destructors 2 2 Copy Constructors 11 2.1 Where Do We Use a Copy Constructor? 12 2.2 Compiler-Generated Copy Constructors............................................
More informationThe Structure of a C++ Program
Steven Zeil May 25, 2013 Contents 1 Separate Compilation 3 1.1 Separate Compilation.......... 4 2 Pre-processing 7 2.1 #include.................. 9 2.2 Other Pre-processing Commands... 14 3 Declarations
More informationTemplates and Vectors
Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector
More informationDue Date: See Blackboard
Source File: ~/2305/lab33.C Input: under control of main function Output: under control of main function Value: 3 The Shell sort, named after its inventor Donald Shell, provides a simple and efficient
More informationC++ Primer for CS175
C++ Primer for CS175 Yuanchen Zhu September 10, 2014 This primer is pretty long and might scare you. Don t worry! To do the assignments you don t need to understand every point made here. However this
More informationLinked Lists. Contents. Steven J. Zeil. July 31, Linked Lists: the Basics 3
Steven J. Zeil July 31, 2013 Contents 1 Linked Lists: the Basics 3 2 Coding for Linked Lists 7 2.1 Traversing a Linked List........................... 10 2.2 Searching a Linked List............................
More informationThe Stack, Free Store, and Global Namespace
Pointers This tutorial is my attempt at clarifying pointers for anyone still confused about them. Pointers are notoriously hard to grasp, so I thought I'd take a shot at explaining them. The more information
More informationCS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015
CS 141 - Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015 You may take this test with you after the test, but you must turn in your answer sheet. This test has the following sections:
More informationCSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion
CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion Review from Lectures 5 & 6 Arrays and pointers, Pointer arithmetic and dereferencing, Types of memory ( automatic, static,
More informationG52CPP C++ Programming Lecture 18
G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Welcome Back 2 Last lecture Operator Overloading Strings and streams 3 Operator overloading - what to know
More informationby Pearson Education, Inc. All Rights Reserved. 2
An important part of every container is the type of iterator it supports. This determines which algorithms can be applied to the container. A vector supports random-access iterators i.e., all iterator
More informationEL2310 Scientific Programming
(pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object
More informationQUIZ. What is wrong with this code that uses default arguments?
QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code
More informationComputer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons
Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite
More informationException Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011
More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors
More informationCS 103 Lab - Party Like A Char Star
1 Introduction In this lab you will implement a "hangman" game where the user is shown blanks representing letter of a word and then tries to guess and fill in the letters with a limited number of guesses.
More informationAgenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures
The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF
More information7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology 8/23/2014. Arrays Hold Multiple Values
Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations Declared using
More informationBefore 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.
Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172 The lab will be on pointers In compensation, no class on Friday, Jan. 31. 1 Consider the bubble function one more
More informationSets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4
Steven J. Zeil July 19, 2013 Contents 1 Overview of Sets and Maps 4 1 2 The Set ADT 6 2.1 The template header................................. 14 2.2 Internal type names.................................
More informationQUIZ. What are 3 differences between C and C++ const variables?
QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,
More informationMemory and Pointers written by Cathy Saxton
Memory and Pointers written by Cathy Saxton Basic Memory Layout When a program is running, there are three main chunks of memory that it is using: A program code area where the program itself is loaded.
More informationG52CPP C++ Programming Lecture 17
G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions
More informationPrinciples of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns
Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns What is an array? Pointers Memory issues The name of the array is actually a memory address. You can prove this by trying to print
More informationErrors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html
Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with
More informationLab#5 Due Wednesday, February 25, at the start of class. Purpose: To develop familiarity with C++ pointer variables
Lab#5 Due Wednesday, February 25, at the start of class Purpose: To develop familiarity with C++ pointer variables Introduction: In this lab, you will learn by experimentation the answers to some questions
More informationChapter 1 Getting Started
Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationCS 103 Unit 12 Slides
1 CS 103 Unit 12 Slides Standard Template Library Vectors & Deques Mark Redekopp 2 Templates We ve built a list to store integers But what if we want a list of double s or char s or other objects We would
More informationG52CPP C++ Programming Lecture 18. Dr Jason Atkin
G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1 Last lecture Operator Overloading Strings and streams 2 Operator overloading - what to know Know that you can change the meaning of operators Know that
More informationNote 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...
CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?
More informationArrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors
Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8
More informationpointers + memory double x; string a; int x; main overhead int y; main overhead
pointers + memory computer have memory to store data. every program gets a piece of it to use as we create and use more variables, more space is allocated to a program memory int x; double x; string a;
More informationCSE 303: Concepts and Tools for Software Development
CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationChapter 16. Templates. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 16 Templates Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Function Templates Syntax, defining Compiler complications Class Templates Syntax Example: array template
More informationDue Date: See Blackboard
Source File: ~/2315/33/lab33.cpp Input: under control of main function Output: under control of main function Value: 3 The Shell sort, named after its inventor Donald Shell, provides a simple and efficient
More informationCA31-1K DIS. Pointers. TA: You Lu
CA31-1K DIS Pointers TA: You Lu Pointers Recall that while we think of variables by their names like: int numbers; Computer likes to think of variables by their memory address: 0012FED4 A pointer is a
More informationHeap Arrays and Linked Lists. Steven R. Bagley
Heap Arrays and Linked Lists Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index Variables and arrays have a type Create our
More informationUnit 1: Preliminaries Part 4: Introduction to the Standard Template Library
Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Engineering 4892: Data Structures Faculty of Engineering & Applied Science Memorial University of Newfoundland May 6, 2010 ENGI
More informationOutline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O
Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references
More informationWhat will happen if we try to compile, link and run this program? Do you have any comments to the code?
1 # include < iostream > 2 3 int main () 4 { 5 std :: cout
More information(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University
(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University Key Concepts 2 Object-Oriented Design Object-Oriented Programming
More information15. Pointers, Algorithms, Iterators and Containers II
498 Recall: Pointers running over the Array 499 Beispiel 15. Pointers, Algorithms, Iterators and Containers II int a[5] = 3, 4, 6, 1, 2; for (int p = a; p < a+5; ++p) std::cout
More informationEE 355 Lab 4 - Party Like A Char Star
1 Introduction In this lab you will implement a "hangman" game where the user is shown blanks representing letter of a word and then tries to guess and fill in the letters with a limited number of guesses
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017
More informationCS 103 Lab 6 - Party Like A Char Star
1 Introduction In this lab you will implement a "hangman" game where the user is shown blanks representing letter of a word and then tries to guess and fill in the letters with a limited number of guesses.
More informationEE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp
1 EE 355 Unit 10 C++ STL - Vectors and Deques Mark Redekopp 2 Templates We ve built a list to store integers But what if we want a list of double s or char s or other objects We would have to define the
More informationVectors and Pointers CS 16: Solving Problems with Computers I Lecture #13
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
More informationCOEN244: Class & function templates
COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library
More informationCS 103 Unit 11. Linked Lists. Mark Redekopp
1 CS 103 Unit 11 Linked Lists Mark Redekopp 2 NULL Pointer Just like there was a null character in ASCII = '\0' whose ue was 0 There is a NULL pointer whose ue is 0 NULL is "keyword" you can use in C/C++
More informationC:\Temp\Templates. Download This PDF From The Web Site
11 2 2 2 3 3 3 C:\Temp\Templates Download This PDF From The Web Site 4 5 Use This Main Program Copy-Paste Code From The Next Slide? Compile Program 6 Copy/Paste Main # include "Utilities.hpp" # include
More informationCSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory
Announcements CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory There will be no lecture on Tuesday, Feb. 16. Prof. Thompson s office hours are canceled for Monday, Feb. 15. Prof.
More informationCommon Modifications of Class Members
Steven Zeil July 13, 2013 Contents 1 Static 2 1.1 Static Data Members...... 2 1.2 Static Function Members... 9 2 const 10 2.1 const Pointers and References 11 2.2 Is your class const-correct?.. 12 1 1
More informationVectors. A Computer Science Tapestry 8.1
Vectors Vectors are homogeneous collections with random access Store the same type/class of object, e.g., int, string, The 1000 th object in a vector can be accessed just as quickly as the 2 nd object
More informationCommon Modifications of Class Members
Steven Zeil July 13, 2013 Contents 1 Static 2 1.1 Static Data Members........... 2 1.2 Static Function Members........ 10 2 const 12 2.1 const Pointers and References..... 13 2.2 Is your class const-correct?.......
More informationC++ For Science and Engineering Lecture 15
C++ For Science and Engineering Lecture 15 John Chrispell Tulane University Wednesday September 29, 2010 Function Review Recall the basics you already know about functions. Provide a function definition.
More informationCS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/
CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationCOSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26
COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.
More informationCS 103 Unit 13 Slides
1 CS 103 Unit 13 Slides C++ References Mark Redekopp 2 Swap Two Variables Classic example of issues with local variables: Write a function to swap two variables Pass-b-value doesn t work Cop is made of
More informationCSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists
Review from Lecture 8 CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately, erasing items
More informationChapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.
Chapter 5 Errors Hyunyoung Lee Based on slides by Bjarne Stroustrup www.stroustrup.com/programming 1 Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must
More informationRecursion. Contents. Steven Zeil. November 25, Recursion 2. 2 Example: Compressing a Picture 4. 3 Example: Calculator 5
Steven Zeil November 25, 2013 Contents 1 Recursion 2 2 Example: Compressing a Picture 4 3 Example: Calculator 5 1 1 Recursion Recursion A function is recursive if it calls itself or calls some other function
More informationInstantiation of Template class
Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double
More informationCS 103 Unit 11. Linked Lists. Mark Redekopp
1 CS 103 Unit 11 Linked Lists Mark Redekopp 2 NULL Pointer Just like there was a null character in ASCII = '\0' whose ue was 0 There is a NULL pointer whose ue is 0 NULL is "keyword" you can use in C/C++
More informationLab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1
Lab 2: Pointers 1. Goals Further understanding of pointer variables Passing parameters to functions by address (pointers) and by references Creating and using dynamic arrays Combing pointers, structures
More informationName SECTION: 12:45 2:20. True or False (12 Points)
Name SECION: 12:45 2:20 rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables
More informationChapter 7: Arrays Copyrig opy ht rig 2012 Pea e rson a Educa Educ ti a on, Inc I. nc
Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Arrays Hold Multiple Values Array variable that can store multiple values of the same type (aggregate type) Values are stored in adjacent memory locations
More information8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017
8. The C++ language, 1 Programming and Algorithms II Degree in Bioinformatics Fall 2017 Hello world #include using namespace std; int main() { } cout
More informationCommon Modifications of Class Members
Steven Zeil July 13, 2013 Contents 1 Static 3 1.1 Static Data Members. 3 1.2 Static Function Members.......................... 18 2 const 22 2.1 const Pointers and References....................... 24
More informationCMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC
CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible
More informationData Structures Lecture 3 Order Notation and Recursion
Data Structures Lecture 3 Order Notation and Recursion 1 Overview The median grade.cpp program from Lecture 2 and background on constructing and using vectors. Algorithm analysis; order notation Recursion
More information1. Which of the following best describes the situation after Line 1 has been executed?
Instructions: Submit your answers to these questions to the Curator as OQ3 by the posted due date and time. No late submissions will be accepted. For the next three questions, consider the following short
More information1 Memory management in C++
Dynamic/Heap Memory CS 101 Abhiram Ranade Goal for today: Understand pointers and memory management in C++ Specific problem to solve: we want to be able to write something like: void turtlemain(){ poly
More informationChapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016
Chapter 6: User-Defined Functions Objectives In this chapter, you will: Learn about standard (predefined) functions Learn about user-defined functions Examine value-returning functions Construct and use
More informationTopics. bool and string types input/output library functions comments memory allocation templates classes
C++ Primer C++ is a major extension of c. It is similar to Java. The lectures in this course use pseudo-code (not C++). The textbook contains C++. The labs involve C++ programming. This lecture covers
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationVector and Free Store (Vectors and Arrays)
DM560 Introduction to Programming in C++ Vector and Free Store (Vectors and Arrays) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides by Bjarne
More informationLinked lists Tutorial 5b
Linked lists Tutorial 5b Katja Mankinen 6 October 2017 Aim Pointers are one of the most powerful tools in C++: with pointers, you can directly manipulate computer memory. However, at first glance they
More information