CS11 Advanced C++ Spring 2018 Lecture 2
|
|
- Kevin Hodges
- 6 years ago
- Views:
Transcription
1 CS11 Advanced C++ Spring 2018 Lecture 2
2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector<T> template working It is still missing some critical functionality Iterators are required for using collections with C++ STL algorithms e.g. sort(), shuffle(), reverse(), Can t use our Vector<T> type with these, yet Our Vector<T> doesn t provide necessary nested member-types e.g. std::vector<t>::value_type or std::vector<t>::const_iterator Our Vector<T> type also doesn t support move semantics Should greatly improve the performance of certain use-cases This week, we will address all of these limitations
3 Standard Template Library (A Review) A very well known part of the C++ Standard Library Primary architect: Alexander Stepanov AT&T Bell Labs, then later Hewlett Packard Andrew Koenig motivated proposal to ANSI/ISO Committee in 1994 Proposal accepted/standardized in 1994 Continuous refinements, increased support Working with the STL requires familiarity with: Class templates and function templates Function pointers Basic data structures / computational complexity 3
4 What Is the Standard Template Library? A set of generic containers, algorithms, and iterators that provide many basic algorithms and data structures of computer science Generic Heavily parameterized; lots of templates! Containers Collections of other objects, with various characteristics Algorithms For manipulating the data stored in containers Iterators A generalization of pointers Cleanly decouple algorithms from containers 4
5 Simple STL Example You want an array of numbers. vector<int> v(3); // Vector of 3 elements v[0] = 7; v[1] = v[0] + 3; v[2] = v[0] + v[1]; Now you want to reverse their order reverse(v.begin(), v.end()); vector<int> is the generic container reverse() is a generic algorithm reverse() uses iterators associated with v 5
6 STL Algorithms Generic function-templates Parameterized on iterator type not container Example: the find() algorithm template <typename InputIterator, typename T> InputIterator find(inputiterator a, InputIterator b, const T& value) { while (a!= b && *a!= value) ++a; return a; } Searches for value in range [a, b) 6
7 Algorithms and Iterators The find() implementation: template <typename InputIterator, typename T> InputIterator find(inputiterator a, InputIterator b, const T& value) { InputIterator isn t a specific type! while (a!= b && *a!= value) ++a; Just needs to support * (dereference), ++ (increment), and equality operators. Pointers also satisfy these requirements float a[5] = { 1.1, 2.3, -4.7, 3.6, 5.2 }; float *pval; // float* as iterators pval = find(a, a + 5, 3.6); 7
8 Concepts This set of functionality required for the iterator-type is called a concept In this case, the concept is named InputIterator A type that satisfies the requirements is said to model the concept Or, it conforms to the concept Given our previous example: float a[5] = { 1.1, 2.3, -4.7, 3.6, 5.2 }; float *pval; // float* as iterators pval = find(a, a + 5, 3.6); int* is a model of InputIterator because int* provides all of the operations that are specified by the InputIterator requirements. 8
9 What About reverse()? The reverse() algorithm needs more! Specifically, its iterators also need -- operator. reverse() s arguments must model the BidirectionalIterator concept. Like InputIterator, but with more requirements. BidirectionalIterator refines the InputIterator concept This is exactly like class-inheritance. Different terms because these aren t classes. 9
10 Concepts?! A major issue with the whole concept thing: Up until C++17, there has been no language support whatsoever for declaring or enforcing the requirements of concepts If you used a type with a template, and the type didn t model the required concept: You get a whole bunch of confusing error messages, none of which say This type is inappropriate to use with this thing! C++17 includes an experimental specification for how to declare and enforce concepts C++20 will [hopefully] include functionality to do this 10
11 Iterator Concept Hierarchy Iterator only supports dereference InputIterator also supports increment Only read support is guaranteed. Only single-pass support guaranteed. ForwardIterator like InputIterator Supports multi-pass algorithms. BidirectionalIterator also supports decrement RandomAccessIterator Supports arbitrary-size steps forward and backward ContiguousIterator Logically-contiguous elements are also physically contiguous 11
12 Output Iterators OutputIterators don t appear in the iterator concept hierarchy Different, very limited set of requirements Support assignment Support increment Support postincrement-and-assign *iter++ = value; For modeling output to the console, sockets, etc. You can write to the current location You can advance to the next location 12
13 Vectors and Iterators Generally, iterators are straightforward to implement begin() member-function returns an iterator that points to the first element end() member-function returns an iterator that points just past the last element Example: v[0] v[1] v[2] v[size-1] (empty) begin() end() Can use to loop over vector contents, etc. for (auto it = v.begin(); it!= v.end(); it++) if (*it == value) return it; Iterator type can be anything that implements all requirements, i.e. * (dereference), ++ (increment), and equality operators
14 Vectors and Iterators (2) std::vector specifies some details about its iterators The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements. This means that a pointer to an element of a vector may be passed to any function that expects a pointer to an element of an array. (since C++03) Can write: Can also write: reverse(v.begin(), v.end()); reverse(&v[0], &v[0] + v.size()); Implication: can use simple pointers as iterators Important note: std::vector s iterators are not simple pointers STL collections also provide rbegin() and rend() reverse iterators Don t mix simple pointers and iterators when working with vectors!
15 Vectors and Iterators (3) Example code: vector<int> v;... // Stuff happens to v auto b = v.begin(); auto e = v.end(); v.push_back(100); Are b and e still valid iterators? b will remain valid, as long as the vector s capacity didn t change e is definitely no longer valid (at least as far as being an end iterator) Certain operations can cause an iterator to become invalid i.e. the operation invalidates the iterator Generally, if a collection changes shape (i.e. reallocations take place) then iterators may become invalidated
16 Iterator Invalidation In general, each container must specify when its iterators may be invalidated Example: A vector s past-the-end iterator is invalidated when an element is inserted or erased A vector s iterators are invalidated when the vector s capacity changes Unfortunately, most collections won t report an error when this occurs Fun experiment: std::vector<int> v; v.reserve(10); auto b = v.begin(); for (int i = 0; i < 1000; i++) { v.push_back(100); cout << *b << "\n"; }
17 Nested Typedefs So far, have been writing, e.g. for (auto it = v.begin(); it!= v.end(); it++) if (*it == value) return it; What is the type of v.begin() or v.end()? C++11 has type-inference, so not as important to know the actual type Many situations where code outside a collection needs to refer to a collection s value-type, iterator-type, etc. Easy way to solve this: STL collections provide nested typedefs that specify common names for their own internal types for (vector<int>::iterator it = v.begin(); it!= v.end(); it++) { if (*it == value) return it; }
18 Nested Typedefs (2) Example implementation: typedef <typename T> class Vector {... public: typedef T value_type; typedef T& reference; typedef const T& const_reference;... // etc. }; Code outside the collection can refer to these typedefs
19 A Data Set Class A simple class to acquire and manage data sets: class DataSet { int capacity; int size; float *samples;... }; samples is an array of float values capacity is the size of the samples array (can be 0) When capacity is 0, samples is set to nullptr size is the number of actual samples in the array at any given time (invariant: size capacity) This is sufficient information to grow samples as needed 19
20 A Data Set Class (2) Our class clearly needs a copy constructor class DataSet { int capacity; int size; float *samples; public:... DataSet(const DataSet &ds); }; Make a deep copy of the data set: capacity = ds.capacity; size = ds.size; samples = new float[capacity]; for (int i = 0; i < size; i++) samples[i] = ds.samples[i]; 20
21 A Data Set Class (3) Methods for our class: class DataSet {... void addsample(float sample); int numsamples() const { return size; } float getsample(int i) const; }; addsample() can store new sample at samples[size] but only if size < capacity! If size == capacity, must increase data set s capacity e.g. capacity = (capacity > 0? capacity * 2 : 16) Allocate a new array of samples; copy contents of old array into new array Delete the old array, and replace it with the new array 21
22 Filtering Data Sets Next, write a function to filter a data set DataSet filterdataset(const DataSet &input, } DataSet output; float maxvalue) { for (int i = 0; i < input.numsamples(); i++) { } float sample = input.getsample(i); if (sample <= maxvalue) return output; output.addsample(sample); Creates a brand new data set, containing results of filtering the input data set 22
23 Filtering Data Sets (2) Example usage: DataSet input; acquiredataset(input); // Any value > 10 is invalid DataSet filtered = filterdataset(input, 10); What does the last line of code actually do? filtered is initialized via copy-constructor 23
24 Filtering Data Sets (3) What does this line of code actually do? DataSet filtered = filterdataset(input, 10); DataSet (temporary) DataSet (local variable) return output; (copy ctor) filterdataset() creates a DataSet local variable that holds the results When the function returns that object, it is copied into a temporary DataSet object representing the entire right-hand side of the assignment Then, function can call destructors on its local objects 24
25 Filtering Data Sets (4) What does this line of code actually do? (cont.) DataSet filtered = filterdataset(input, 10); DataSet (filtered) DataSet (temporary) copy ctor DataSet (local variable) return output; (copy ctor) Next, the temporary object on the RHS is passed to the copy-constructor for filtered Copy-constructor makes a deep copy of samples Finally, the temporary object is also destructed 25
26 Filtering Data Sets (5) What does this line of code actually do? (cont.) DataSet filtered = filterdataset(input, 10); DataSet (filtered) DataSet (temporary) copy ctor DataSet (local variable) return output; (copy ctor) Note: Many compilers optimize this to pass the returned object directly to the final copy constructor Avoids the overhead of constructing and destructing the temporary object Still, we must make a deep copy of an object that we know is about to be destructed 26
27 What If We know that the object inside filterdataset() will be destructed when the function returns DataSet filtered = filterdataset(input); What if we could just move the contents of the returned object directly into filtered? Avoid having to make another deep copy inside the copy constructor Avoid having to clean up heap-allocated data in the object constructed by filterdataset() This optimization became possible in C++11, with the introduction of move semantics 27
28 Lvalues, Rvalues and Rvalue References Our example: DataSet filtered = filterdataset(input); filtered is an lvalue It can be the target of an assignment It persists across multiple statements The object returned by filterdataset() is an rvalue It is a temporary object that will be destructed at the end of statement execution C++11 introduces rvalue references T&& is an rvalue reference to an object of type T Temporary values produced by expressions can be manipulated via rvalue references 28
29 Move Constructors Can define a move constructor for our DataSet class Construction from a temporary object, e.g. DataSet filtered = filterdataset(input); How to implement this constructor? DataSet(DataSet &&ds) { capacity = ds.capacity; size = ds.size; samples = ds.samples; } Are we done? No: also need to set ds.samples = nullptr! Otherwise, temporary object will deallocate our samples when it goes out of scope 29
30 Move Constructors (2) Correct move constructor: DataSet(DataSet &&ds) { capacity = ds.capacity; size = ds.size; samples = ds.samples; ds.samples = nullptr; } 30
31 Move-Assignment Operators Similarly, need to create a move-assignment operator Assignment from a temporary object, e.g. DataSet filtered; filtered = filterdataset(input); Move-assignment operator follows the same idea as the move constructor: DataSet & operator=(dataset &&ds) { capacity = ds.capacity; size = ds.size; samples = ds.samples; ds.samples = nullptr; return *this; } Are we done? No: also need to clean up any samples we had before 31
32 Move-Assignment Operators (2) Now are we done? DataSet & operator=(dataset &&ds) { capacity = ds.capacity; size = ds.size; delete[] samples; samples = ds.samples; ds.samples = nullptr; return *this; } No: we really should also guard against self-assignment 32
33 Move-Assignment Operators (3) Final implementation: DataSet & operator=(dataset &&ds) { if (this!= &ds) { capacity = ds.capacity; size = ds.size; delete[] samples; samples = ds.samples; ds.samples = nullptr; } return *this; } 33
34 Named Data Sets Add a name to our data sets: class DataSet { string name; }; int capacity; int size; float *samples;... 34
35 Named Data Sets (2) Now we have a new problem in move operations: DataSet(DataSet &&ds) { name = ds.name; capacity = ds.capacity; size = ds.size; samples = ds.samples; ds.samples = nullptr; } ds.name is considered an lvalue, so it will be copied instead of being moved Need to tell the compiler it s okay to move the contents of ds.name because it s also temporary 35
36 std::move() Use the std::move() utility function to tell the compiler that something is movable #include <utility> DataSet(DataSet &&ds) { name = std::move(ds.name); capacity = ds.capacity; size = ds.size; samples = ds.samples; ds.samples = nullptr; } std::move() returns an rvalue reference to its argument 36
37 std::move() (2) Generally only need std::move() when your class has datamembers that are objects class DataSet { string name; // Class member! int capacity; int size; float *samples;... }; Generally shouldn t need std::move() very often 37
38 The Rule of Three Five Last time we discussed the Rule of Three: If your class implements a custom copy-constructor, a custom copyassignment operator, and/or a custom destructor, it should probably implement all three. Rule of Three was most relevant until move semantics were introduced into C Now, it s a very good idea to follow the Rule of Five: If your class implements any of the following: A custom copy-constructor A custom copy-assignment operator A custom destructor A custom move-constructor A custom move-assignment operator it should probably implement all five.
39 The Rule of Five The Rule of Five: If your class implements any of the following: A custom copy-constructor A custom copy-assignment operator A custom destructor A custom move-constructor A custom move-assignment operator it should probably implement all five. Are all of these required for correctness? Only the copy-constructor, copy-assignment operator, and destructor are required for correctness Move-constructor and move-assignment operator are focused on achieving high performance Rule of Three is focused on correctness; Rule of Five on correctness and good performance
CS11 Advanced C++ Fall Lecture 1
CS11 Advanced C++ Fall 2006-2007 Lecture 1 Welcome! ~8 lectures Slides are posted on CS11 website http://www.cs.caltech.edu/courses/cs11 ~6 lab assignments More involved labs 2-3 week project at end CS
More informationSTL Quick Reference for CS 241
STL Quick Reference for CS 241 Spring 2018 The purpose of this document is to provide basic information on those elements of the C++14 standard library we think are most likely to be needed in CS 241.
More informationuse static size for this buffer
Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation
More informationCS11 Advanced C++ Spring 2018 Lecture 1
CS11 Advanced C++ Spring 2018 Lecture 1 Welcome to CS11 Advanced C++! A deeper dive into C++ programming language topics Prerequisites: CS11 Intro C++ track is strongly recommended (obvious) You should
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 informationSTL: C++ Standard Library
STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms
More information04-19 Discussion Notes
04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here
More informationCS201 Some Important Definitions
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
More information6.096 Introduction to C++
MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Massachusetts Institute
More informationCh. 12: Operator Overloading
Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42
More informationLecture 15a Persistent Memory & Shared Pointers
Lecture 15a Persistent Memory & Shared Pointers Dec. 5 th, 2017 Jack Applin, Guest Lecturer 2017-12-04 CS253 Fall 2017 Jack Applin & Bruce Draper 1 Announcements PA9 is due today Recitation : extra help
More informationLecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.
Lecture 21 Standard Template Library STL: At a C++ standards meeting in 1994, the committee voted to adopt a proposal by Alex Stepanov of Hewlett-Packard Laboratories to include, as part of the standard
More informationCOMP6771 Advanced C++ Programming
1.... COMP6771 Advanced C++ Programming Week 5 Part One: Exception Handling 2016 www.cse.unsw.edu.au/ cs6771 2.... Memory Management & Exception Handling.1 Part I: Exception Handling Exception objects
More informationObjects Managing a Resource
Objects Managing a Resource 1 What is a Resource Respects Release/Acquire protocol files (open/close) memory allocation (allocate/free) locks (acquire/release). 2 What is a Resource Objects when constructed,
More informationSTL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms
STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed
More informationObject-Oriented Principles and Practice / C++
Object-Oriented Principles and Practice / C++ Alice E. Fischer October 10, 2016 OOPP / C++ Lecture 7... 1/15 Construction and Destruction Kinds of Constructors Move Semantics OOPP / C++ Lecture 7... 2/15
More informationOverview of C Feabhas Ltd 2012
1 2 Copying objects may not be the best solution in many situations. In such cases we typically just want to transfer data from one object to another, rather than make an (expensive, and then discarded)
More informationCSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists
Review from Lecture 8 CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators,
More informationC The new standard
C++11 - The new standard Lars Kühne Institut für Informatik Lehrstuhl für theoretische Informatik II Friedrich-Schiller-Universität Jena January 16, 2013 Overview A little bit of history: C++ was initially
More informationSTL in Action: Helper Algorithms
STL in Action: Helper Algorithms By Graham Glass Abstract This article introduces a new column called STL in Action. Each installment will describe a way to either utilize or extend the C++ Standard Template
More informationProgramming in C++ using STL. Rex Jaeschke
Programming in C++ using STL Rex Jaeschke Programming in C++ using STL 1997, 1999, 2002, 2007, 2009 Rex Jaeschke. All rights reserved. Edition: 2.0 All rights reserved. No part of this publication may
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 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 informationCOMP6771 Advanced C++ Programming
1. COMP6771 Advanced C++ Programming Week 4 Part One: (continued) and 2016 www.cse.unsw.edu.au/ cs6771 2. Inline Constructors, Accessors and Mutators Question (from 2015): In the week 3 examples, constructors
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 informationWorking with Batches of Data
Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html 2 Abstract So far we looked at simple read a string print a string problems. Now we will look at more complex problems
More informationCS11 Advanced C++ Fall Lecture 7
CS11 Advanced C++ Fall 2006-2007 Lecture 7 Today s Topics Explicit casting in C++ mutable keyword and const Template specialization Template subclassing Explicit Casts in C and C++ C has one explicit cast
More informationSpecial Member Functions
CS 247: Software Engineering Principles Special Member Functions Readings: Eckel, Vol. 1 Ch. 11 References and the Copy Constructor Ch. 12 Operator Overloading ( operator= ) U Waterloo CS247 (Spring 2017)
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 11 October 3, 2018 CPSC 427, Lecture 11, October 3, 2018 1/24 Copying and Assignment Custody of Objects Move Semantics CPSC 427, Lecture
More information04-17 Discussion Notes
04-17 Discussion Notes PIC 10B Spring 2018 1 RAII RAII is an acronym for the idiom Resource Acquisition is Initialization. What is meant by resource acquisition is initialization is that a resource should
More informationCS
CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and
More information19. Dynamic Data Structures II
Different Memory Layout: Linked List 19. Dynamic Data Structures II Linked Lists, Vectors as Linked Lists No contiguous area of memory and no random access Each element points to its successor Insertion
More informationCS 32. Lecture 5: Templates
CS 32 Lecture 5: Templates Vectors Sort of like what you remember from Physics but sort of not Can have many components Usually called entries Like Python lists Array vs. Vector What s the difference?
More informationObject-Oriented Principles and Practice / C++
Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions
More informationRvalue References & Move Semantics
Rvalue References & Move Semantics PB173 Programming in Modern C++ Nikola Beneš, Vladimír Štill, Jiří Weiser Faculty of Informatics, Masaryk University spring 2016 PB173 Modern C++: Rvalue References &
More informationCS 162, Lecture 25: Exam II Review. 30 May 2018
CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you
More informationVector and Free Store (Pointers and Memory Allocation)
DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides
More informationCh. 11: References & the Copy-Constructor. - continued -
Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed
More informationChapter 5. The Standard Template Library.
Object-oriented programming B, Lecture 11e. 1 Chapter 5. The Standard Template Library. 5.1. Overview of main STL components. The Standard Template Library (STL) has been developed by Alexander Stepanov,
More informationCopyie Elesion from the C++11 mass. 9 Sep 2016 Pete Williamson
Copyie Elesion from the C++11 mass 9 Sep 2016 Pete Williamson C++ 11 is a whole new language Links to learning more: http://en.cppreference.com/w/cpp/language/copy_elision https://engdoc.corp.google.com/eng/doc/devguide/cpp/cpp11.shtml?cl=head
More informationDynamic Data Structures
Dynamic Data Structures We have seen that the STL containers vector, deque, list, set and map can grow and shrink dynamically. We now examine how some of these containers can be implemented in C++. To
More informationCOMP6771 Advanced C++ Programming
1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout
More informationCS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms
CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()
More informationChapter 17 vector and Free Store
Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:
More informationCS11 Intro C++ Spring 2018 Lecture 2
CS11 Intro C++ Spring 2018 Lecture 2 C++ Compilation You type: g++ -Wall -Werror units.cpp convert.cpp -o convert What happens? C++ compilation is a multi-step process: Preprocessing Compilation Linking
More informationItem 3: Predicates, Part 2: Matters of State
ITEM1_11new.fm Page 1 Tuesday, November 27, 2001 12:41 PM Item 3: Predicates, Part 2: Matters of State ITEM 3: PREDICATES, PART 2: MATTERS OF STATE DIFFICULTY: 7 Following up from the introduction given
More information1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!
//Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new
More informationThis chapter serves mainly to gather and organize information about iterators. Some new concepts are also introduced for completeness.
Iterators Overview We have introduced, used, built, and studied iterators in several contexts, including List, TDeque, and TVector. We have seen that ordinary pointers also can be thought of as iterators
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 informationAllocation & Efficiency Generic Containers Notes on Assignment 5
Allocation & Efficiency Generic Containers Notes on Assignment 5 CS 311 Data Structures and Algorithms Lecture Slides Friday, October 30, 2009 Glenn G. Chappell Department of Computer Science University
More informationCS11 Advanced C++ Fall Lecture 3
CS11 Advanced C++ Fall 2006-2007 Lecture 3 Today s Topics C++ Standard Exceptions Exception Cleanup Fun with Exceptions Exception Specifications C++ Exceptions Exceptions are nice for reporting many errors
More informationCSE 333 Lecture smart pointers
CSE 333 Lecture 14 -- smart pointers Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New exercise out today, due Wednesday morning Exam Friday
More informationObject-Oriented Programming
s iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 21 Overview s 1 s 2 2 / 21 s s Generic programming - algorithms are written with generic types, that are going to be specified later. Generic programming
More informationContainer Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11
Di erent Kinds of Containers Container Notes A container is an object that stores other objects and has methods for accessing the elements. There are two fundamentally di erent kinds of containers: Sequences
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 informationCSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation
Today CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation Another vector operation: pop back Erasing items from vectors is inefficient! Iterators and iterator operations
More informationCS11 Introduction to C++ Fall Lecture 6
CS11 Introduction to C++ Fall 2006-2007 Lecture 6 Today s Topics C++ exceptions Introduction to templates How To Report Errors? C style of error reporting: return values For C Standard Library/UNIX functions,
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 informationFunction Templates. Consider the following function:
Function Templates Consider the following function: void swap (int& a, int& b) { int tmp = a; a = b; b = tmp; Swapping integers. This function let's you swap the contents of two integer variables. But
More informationTDDD38 - Advanced programming in C++
TDDD38 - Advanced programming in C++ STL II Christoffer Holm Department of Computer and information science 1 Iterators 2 Associative Containers 3 Container Adaptors 4 Lambda Functions 1 Iterators 2 Associative
More informationSixth lecture; classes, objects, reference operator.
Sixth lecture; classes, objects, reference operator. 1 Some notes on the administration of the class: From here on out, homework assignments should be a bit shorter, and labs a bit longer. My office hours
More informationRvalue References, Move Semantics, Universal References
Rvalue References, Move Semantics, Universal References PV264 Advanced Programming in C++ Nikola Beneš Jan Mrázek Vladimír Štill Faculty of Informatics, Masaryk University Spring 2018 PV264: Rvalue References,
More informationToday. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2
TEMPLATES Today This lecture looks at techniques for generic programming: Generic pointers Templates The standard template library Thebestreferenceis: http://www.cppreference.com/index.html andyoucanalsoconsultchapters6amd7inthetextbook.
More informationObject-Oriented Principles and Practice / C++
Object-Oriented Principles and Practice / C++ Alice E. Fischer May 13, 2013 OOPP / C++ Lecture 7... 1/27 Construction and Destruction Allocation and Deallocation Move Semantics Template Classes Example:
More informationOutline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation
Outline EDAF30 Programming in C++ 4. The standard library. Algorithms and containers. Sven Gestegård Robertz Computer Science, LTH 2018 1 Type inference 2 3 The standard library Algorithms Containers Sequences
More informationCOP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008
COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008 Lab topic: 1) Take Quiz 4 2) Discussion on Assignment 2 Discussion on Assignment 2. Your task is to
More informationTemplates Templates are functions or classes that are parameterized. We have already seen a few in STL:
Templates Templates are functions or classes that are parameterized. We have already seen a few in STL: std::vector< int > std::vector< double > std::list< std::vector< >> std::unordered_map< int, bool
More informationLecture 13: more class, C++ memory management
CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 13:
More informationClasses in C++98 and C++11
Classes in C++98 and C++11 January 10, 2018 Brian A. Malloy Slide 1 of 38 1. When we refer to C++98, we are referring to C++98 and C++03, since they differ only slightly. C++98 contained 3 types of constructors,
More informationC++ for Java Programmers
Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even
More informationWhen we program, we have to deal with errors. Our most basic aim is correctness, but we must
Chapter 5 Errors When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications, incomplete programs, and our own errors. When
More informationCSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington
CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning
More information3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.
3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.
More informationPointer Basics. Lecture 13 COP 3014 Spring March 28, 2018
Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory
More informationTemplate based set of collection classes STL collection types (container types)
STL Collection Types Template based set of collection classes STL collection types (container types) Sequences vector - collection of elements of type T list - doubly linked list, only sequential access
More informationThe C++ Object Lifecycle. EECS 211 Winter 2019
The C++ Object Lifecycle EECS 211 Winter 2019 2 Initial code setup $ cd eecs211 $ curl $URL211/lec/09lifecycle.tgz tar zx $ cd 09lifecycle 3 Road map Owned string type concept Faking it An owned string
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 informationC++ for Java Programmers
Lecture 6 More pointing action Yesterday we considered: Pointer Assignment Dereferencing Pointers to Pointers to Pointers Pointers and Array Pointer Arithmetic 2 Todays Lecture What do we know 3 And now
More informationModern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced
Department I - C Plus Plus Advanced Modern and Lucid C++ Advanced for Professional Programmers Part 3 Move Semantics Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 09.03.2018 HS2018 Move Semantics 2
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 informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
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 informationCSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators
Review from Lecture 7 CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors
More informationPart X. Advanced C ++
Part X Advanced C ++ topics Philip Blakely (LSC) Advanced C++ 158 / 217 References The following are highly regarded books. They are fairly in-depth, and I haven t read them in their entirity. However,
More informationMajor Language Changes, pt. 1
C++0x What is C++0x? Updated version of C++ language. Addresses unresolved problems in C++03. Almost completely backwards compatible. Greatly increases expressiveness (and complexity!) of language. Greatly
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 informationAssignment 1: grid. Due November 20, 11:59 PM Introduction
CS106L Fall 2008 Handout #19 November 5, 2008 Assignment 1: grid Due November 20, 11:59 PM Introduction The STL container classes encompass a wide selection of associative and sequence containers. However,
More informationImplementing vector<>
Lecture 26 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Vector Vector is the most useful container Simple Compactly stores elements of a given type Efficient
More informationVector. Vector Class. class Vector { public: typedef unsigned int size_type;
Vector Arrays in C++ must be pre-allocated to accomodate the maximum number of elements. Should an application attempt to add more than this number, the program may abort, or alter storage of adjacent
More informationChapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.
Chapter 10 Pointers and Dynamic Arrays Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic
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 informationPointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology
Introduction to C++ Massachusetts Institute of Technology ocw.mit.edu 6.096 Pointers 1 Background 1.1 Variables and Memory When you declare a variable, the computer associates the variable name with a
More informationSpecial Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions
Special Member Functions CS 247: Software Engineering Principles Special Member Functions Readings: Eckel, Vol. 1 Ch. 11 References and the Copy Constructor Ch. 12 Operator Overloading ( operator= ) C++
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 informationCS11 Introduction to C++ Fall Lecture 7
CS11 Introduction to C++ Fall 2012-2013 Lecture 7 Computer Strategy Game n Want to write a turn-based strategy game for the computer n Need different kinds of units for the game Different capabilities,
More informationExercise 6.2 A generic container class
Exercise 6.2 A generic container class The goal of this exercise is to write a class Array that mimics the behavior of a C++ array, but provides more intelligent memory management a) Start with the input
More informationChapter 17 vector and Free Store. Bjarne Stroustrup
Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:
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 informationTHE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming
THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming What the heck is STL???? Another hard to understand and lazy to implement stuff? Standard Template Library The standard template
More informationCSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation
CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation Review from Lectures 7 Algorithm Analysis, Formal Definition of Order Notation Simple recursion, Visualization
More information