C++ (7. Vorlesung) Exercise Discussion, Advanced Templates
|
|
- Reginald Page
- 6 years ago
- Views:
Transcription
1 C++ (7. Vorlesung) Exercise Discussion, Advanced Templates Thomas Gschwind 1
2 Agenda Exercise Discussions RPN Calculator Complex numbers (Operators) min (Complex) Connect 4 finding whether the opponent can win pvector with strings Advanced Template Topics Template Implementation: C++ vs. Java vs. C# Traits Dynamic Static Algorithm Selection 2
3 Complex numbers The standard complex class is trivial Don t use free-standing operators in combination with friends Make the operators members of the class Input and output is the only exception RPN calculator with complex Many colleagues did not implement it Many colleagues used the C++11 complex class (my mistake) Hint, you need to ensure that you have all the operators used by the RPN calculator: >>, <<, ==,!=, <, 3
4 RPN<complex> and min Yes, there is no ordering defined on complex classes Solutions I have seen/heard: Define min for complex as a<b iff a < b Creative solution but not really nice min function part of the RPN calculator => bad choice In C++ we don t have to cram random stuff into random classes Specialization for complex requires rewriting of RPN calculator Adapt min to return a pointer to the minimum, overload for complex and return NULL Creative solution but makes min not really nice to use Overload min for complex and throw an exception My favorite solution 4
5 pvector<string> Many colleagues tried the pvector with strings and did not observe anything Hello, World, Somestring, Apple, Banana : are not really useful strings to test something This is interesting, Tab\tstop, And\nnewlines?, Umlaute? ÄÖÜäöü : are better strings Then we would realize that white spaces are problematic with our pvector implementation, especially \n should have been obvious So, how do we solve this? This is the matter of today s lecture. 5
6 Connect 4: Checking if the other player could win A minority of colleagues look for 3 stones in a row (buggy x_xx) or a pattern of 3 in a series of 4 fields (better but clumsy) Most colleagues drop a stone and use the has_won method You don t need to copy the playfield every time, just remove the stone after the test Do this for every column dead simple Yes, with this implementation, you can already recursively start computing the next possible move for the opponent, etc. 6
7 Connect 4: Interoperability Exercises Get an implementation from your colleague almost nobody did this Do it for the next exercise when we do connect 4 with inheritance A few problems you would have encountered (or will encounter) You may want to extend your playfield The playfield your computer player receives, might be different if running in a colleagues implementation Just use the provided methods, not more If you rely on your own playfield, copy whatever you get into your own playfield that provides all the extra methods problem solved Maybe you do not want to extend your main playfield but use your own playfield class inside the computer player anyway The above are just some ideas to get you thinking! 7
8 Agenda Exercise Discussions RPN Calculator Complex numbers (Operators) min (Complex) Connect 4 finding whether the opponent can win pvector with strings Advanced Template Topics Template Implementation: C++ vs. Java vs. C# Traits Dynamic Static Algorithm Selection 8
9 C++ Templates Implementation C++ creates a new artifact for each new use of a template (almost, modern C++ compilers do some optimization) Similar to advanced C macros
10 C++ Templates Implementation (cont d) template<typename T> inline T min(t a, T b) { return a<b?a:b; } const double pi= ; void f() { // create implementation for min( ,1.0); // min<double> min('a','z'); // min<char> min(1,26); // min<int> min(pi, ); // already created min<char>('a',26); // already created min( ,1.0); // already created }
11 C++ Templates Consequences C++ creates a new artifact for each new use of a template Uses more memory Templates need to be defined in the header file (Otherwise, the compiler cannot instantiate them when they are used) Can be used in combination with built-in types Can be used in combination with non-typenames (e.g., ints, chars, ) Better optimization since the template can be optimized for each specific template argument
12 C++ Templates Question What if we have multiple source files instantiating the same template? file1.cc instantiating vector<int> file2.cc instantiating vector<int> Will the code for vector<int> be generated twice once for each object file? Will the executables be double the size when main.cc uses both of them?
13 C++ Templates Question What if we have multiple source files instantiating the same template? file1.cc instantiating vector<int> file2.cc instantiating vector<int> Will the code for vector<int> be generated twice once for each object file? Yes! Will the executables be double the size when main.cc uses both of them? No! Why? The corresponding code of the templates is put into a COMDAT section of the object file. The linker only uses the first such section with the same name.
14 Java Generics Implementation Java Generics are implemented using type erasure All the template parameters are internally replaced with their type bound (Object by default) The compiler inserts casts as necessary
15 Java Generics Implementation Source Code public class Iterator<E> { E next(); boolean hasnext(); } Iterator<String> iter= ; while(iter.hasnext()) { String s=iter.next(); } Generated Code public class Iterator { Object next(); boolean hasnext(); } Iterator iter= ; while(iter.hasnext()) { String s=(string) iter.next(); }
16 Java Generics Consequences Java keeps only one copy of the class Java Generics cannot be used with primitive types Need to be encapsulated in the corresponding wrapper class Java does this since quite some time automatic BUT generating wrappers requires memory, stresses the garbage collector Allows forward and backward compatibility with existing code public String oops(integer x) { List<String> ys = new LinkedList<String>(); List xs = ys; xs.add(x); // compile-time unchecked warning return ys.iterator().next(); } // run-time error
17 Java Generics Consequences (cont d) Java keeps only one copy of the class Uses more memory many casts need to be inserted Programs can be unsafe although they look safe (but the compiler will warn about it) Allows forward and backward compatibility with existing code Cannot create elements of E No new E or new E[] Especially the latter can be annoying, need to use Object[] and a lot of (E) casts which are unsafe JIT cannot optimize for different parameterizations
18 C# Generics Implementation C# thought about Generics from the start Unlike the Java VM, the CLR is already generic Generics can be parameterized with primitive types CLR JIT can optimize code for different parameterizations
19 C# Generics Consequences Templates are stored as such in the byte-code Can be used for built-in types Can use arrays of type T. Cannot be used in combination with non-typenames (e.g., ints, chars, ) Better optimization since the template can be optimized for each specific template argument Uses more memory Is somewhere between C++ and Java
20 Agenda Exercise Discussions RPN Calculator Complex numbers (Operators) min (Complex) Connect 4 finding whether the opponent can win pvector with strings Advanced Template Topics Template Implementation: C++ vs. Java vs. C# Traits Dynamic Static Algorithm Selection 20
21 pvector<string> Implement the persistent vector data type. Experiment with the persistent vector and use it in combination with different data types. What do you observe? Why do you observe that behavior? How can it be changed? What happens if we pass the pvector around? 21
22 A Persistent pvector Class (cont d) pvector.cc template<typename T> class pvector { string filename; vector<t> v; void readvector() { ifstream ifs(filename); for(;;) { What if we use string as type parameter? Reads a string up to the next whitespace T x; ifs >> x; if(!ifs.good()) break; v.push_back(x); } } void writevector() { ofstream ofs(filename); Writes a string with and without whitespace vector<t>::iterator fst=v.begin(), lst=v.end(); while(fst!=lst) ofs << *fst++ << endl; } 22
23 pvector for string? Use partial specialization Partial specialization allows us to change the implementation of a template for a specific class Very easy to implement but very repetitive pvector.cc template<> class pvector<string> { string filename; vector<string> v; void readvector() { } void writevector() { } // repeat all the other methods as is 23
24 pvector for string? (cont d) Use inheritance Need to change readvector and writevector in parent class to be virtual Implied dynamic dispatch although unnecessary We need a new class with a new name pvectorstring? pvectorstring.cc class pvectorstring : pvector<string> { virtual void readvector() { } virtual void writevector() { } } 24
25 pvector for string? (cont d) Factor out the persistence logic into a separate interface Yes, not so repetitive Yes, the persistence logic can be reused template<typename T> struct pvector_serialize { virtual void readvector(string fn) = 0; virtual void writevector(string fn) = 0; } 25
26 pvector with inheritance based serializer Pass serializer to pvector in constructor template<typename T> class pvector { string filename; vector<t> v; pvector_serializer<t> *serializer; public: pvector(string fname, pvector_serializer<t> *ser) : filename(fname), serializer(ser) { serializer->readvector(); } }; ~pvector() { serializer->writevector(); } 26
27 pvector for string? (cont d) Current solution is rather coarse grained Would be better to just factor out the read and write function Gives better reuse (left as exercise) template<typename T> struct element_serializer { virtual void read(ifstream &i, T &elem) = 0; virtual void write(ofstream &o, const T &elem) = 0; } Trouble is we always use virtual method calls although We know the type T And typically the serializer to be used upfront Templates, if used correctly allow the same mechanism as we just implemented with inheritance Same functionality, same everything, just more efficient 27
28 Traits are similar to Inheritance but Different Inheritance allows to define an interface to be provided by subtypes Traits define an interface to be used for any type AND provide a default implementation as well pvector.cc template<typename T> struct persister { static void read(ifstream &i, T &elem) { } static void write(ofstream &o, const T &elem) { } } With inheritance subtypes may override methods With traits, specializations may override methods pvector.cc Default implementation Same principle as for min<string> template<> struct persister<string> { static void read(ifstream &i, T &elem) { } static void write(ofstream &o, const T &elem) { } } 28
29 Pvector Refactoring First, let s refactor the pvector class to move the read and write methods into external classes 29
30 pvector for string? (cont d) pvector.cc template<typename T> struct persister { static void read(ifstream &i, T &elem) { } static void write(ofstream &o, const T &elem) { } } template<> struct persister<string> { static void read(ifstream &i, T &elem) Depending { } on the static void write(ofstream &o, const type T of &elem) container { } } template<typename T> class pvector { void writevector() { ofstream ofs(filename); <T> in use can be determined by the compiler vector ::iterator fst=v.begin(), lst=v.end(); while(fst!=lst) persister <T> ::write(ofs,*fst++); } 30
31 pvector for string? (cont d) Factor out the persistence logic in a separate class Yes, not so repetitive Yes, the persistence logic can be reused Yes, everything determined at compile time But, what if we want to use different persisters? Now, let s use our traits class in a polymorphic way Sort of like we are used from object-oriented programming Except that types are resolved during compile time 31
32 Traits are similar to Inheritance but Different Inheritance allows us to use different implementations Similarly, allow to specify the use of different implementations, independently of the trait s type The key difference is that all type inference is known, verified, and resolved during compile time pvector.cc template<typename T, typename P> class pvector { void writevector() { ofstream ofs(filename); vector<t>::iterator fst=v.begin(), lst=v.end(); while(fst!=lst) P<T>::write(ofs,*fst++); } foo.cc pvector<string, persister<string> > myvector; 32
33 pvector for string? (cont d) Make the persistence class generic Yes, now we can even specify the persister Yes, the code is as readable as generic Java code Yes, BUT creating a new object becomes tedious Are we picky?!? 33
34 pvector for string? (cont d) pvector.cc pvector.cc foo.cc template<typename T, typename P> class pvector { void writevector() { Typically called ofstream ofs(filename); a traits class vector<t>::iterator fst=v.begin(), lst=v.end(); while(fst!=lst) P<T>::write(*fst++); } template<typename T, typename P=persister<T> > class pvector { void writevector() { ofstream ofs(filename); This is not the most pretty implementation vector<t>::iterator fst=v.begin(), lst=v.end(); while(fst!=lst) P::write(*fst++); } pvector<string> myvector; 34
35 pvector for string Beauty Contest pvector.cc pvector.cc template<typename T, typename P> class pvector { void writevector() { ofstream ofs(filename); vector<t>::iterator fst=v.begin(), lst=v.end(); while(fst!=lst) P<T>::write(*fst++); } template<typename T, typename P=persister<T> > class pvector { typedef P persister; typedef typename vector<t>::iterator iterator; void writevector() { ofstream ofs(filename); This helps the compiler to identify that the following is a typename iterator fst=v.begin(), lst=v.end(); while(fst!=lst) persister::write(*fst++); } 35
36 Agenda Advanced Uses of Templates Traits Not just typenames? C++ Standard Library II Iterators & Algorithms Binders 36
37 Different Types of Iterators Category output input forward bidirectional randomaccess Abbrev. Out In For Bi Ran Read =*p =*p =*p =*p Access -> -> -> -> [] Write *p= *p= *p= Iteration Compare ==!= ==!= ==!= *p= = = == < <=!= > >= 37
38 Types of Iterators (cont d) Input Output Forward Bidirectional struct input_iterator_tag {}; struct output_iterator_tag {}; struct forward_iterator_tag : public input_iterator_tag {}; struct bidirectional_iterator_tag : public forward_iterator_tag {}; struct random_access_iterator_tag : public bidirectional_iterator_tag {}; Random Access 38
39 Iterator Tags? Algorithm selection Saves typing overhead Simulation of bound genericity 39
40 Why Iterator Tags? (cont d) iterator template <class In> iterator_traits<in>::difference_type distance(in first,in last, input_iterator_tag dummy) { iterator_traits<in>::difference_type n = 0; while(first!=last) { ++first; ++n; } return n; } template <class Ran> iterator_traits<ran>::difference_type distance(ran first,ran last, random_access_iterator_tag dummy) { return last-first; } template <class I> inline iterator_traits<i>::difference_type distance(i first,i last) { typedef typename iterator_traits<i>::iterator_category cat; return distance(first,last, cat()); } 40
41 iterator_traits iterator template <class Iter> struct iterator_traits<iter> { typedef typename Iter::iterator_category iterator_category; typedef typename Iter::value_type value_type; typedef typename Iter::difference_type difference_type; typedef typename Iter::pointer pointer; typedef typename Iter::reference reference; }; template <class T> struct iterator_traits<t*> { typedef random_access_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef T& reference; }; 41
42 Advise Decide which algorithms you want; parameterize them so that they work for a variety of suitable types and data structures. Bjarne Stroustrup 42
43 Summary Exercise Discussions RPN Calculator Complex numbers (Operators) min (Complex) Connect 4 finding whether the opponent can win pvector with strings Advanced Template Topics Template Implementation: C++ vs. Java vs. C# Traits Dynamic Static Algorithm Selection 43
44 Exercise 1 Adapt your persistent pvector to make use of the new persister trait. Also implement a pset that implements a persistent set (based on std::set). 44
45 Exercise 2 Extend your dictionary program Instead of printing out all unknown words, your program should allow the user to correct them or insert them into the dictionary if spelled correctly but not in the dictionary. Make use of your persistent set implementation form exercise 1. Please make a copy of the old version of the dictionary program. 45
46 Exercise 3 Implement a template based version of the Connect 4 game where players. Connect 4 builds on a playing field composed out of 7 columns each having 6 rows. When a player puts a stone into a column, gravity pulls the stone towards the lowest unoccupied column. The player who first has 4 stones in a row (horizontally, vertically, diagonally) wins. After each turn display the game field using simple ASCII graphics. Implement the game in such a way that players can be exchanged easily using templates. The precise interfaces to follow will be published at the lecture s homepage. It is important that you follow these interfaces religiously. 46
47 Exercise 4 Implement a computer player. Again, the computer player of this version does not have to be intelligent. At a minimum, however, the computer player should be able to identify whether he can win the game by placing a stone. Let your computer player compete against computer players from your colleagues. 47
48 Exercise 5: rpn_calculator<complex> Make sure the RPN calculator works with both with your implementation of complex numbers With the C++11 version of complex numbers 48
49 Next Lecture Algorithms, Binders, and Programming with Templates Have fun solving the examples! See you next week! 49
50 Agenda Exercise Discussions RPN Calculator Complex numbers (Operators) min (Complex) Connect 4 finding whether the opponent can win pvector with strings Advanced Template Topics Template Implementation: C++ vs. Java vs. C# Traits Dynamic Static Algorithm Selection 50
Software Development with C++ Templates
Software Development with C++ Templates Lab Submission 1 Exercises should be solved in groups of two. However, with approval from the lecturer, exercises may also be solved alone or in groups of three.
More informationThe following is an excerpt from Scott Meyers new book, Effective C++, Third Edition: 55 Specific Ways to Improve Your Programs and Designs.
The following is an excerpt from Scott Meyers new book, Effective C++, Third Edition: 55 Specific Ways to Improve Your Programs and Designs. Item 47: Use traits classes for information about types. The
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Traits and Policies Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 11. Juli 2017
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Traits and Policies Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer Semester
More informationBring Back the Obvious Definition of count()
Bring Back the Obvious Definition of count() Bjarne Stroustrup AT&T Bell Laboratories Murray Hill, New Jersey 07974 Alex Stepanov, Matt Austern Silicon Graphics Inc. ABSTRACT #X3J16/96-0029 WG21/N0847
More informationPolymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types.
Session 4 - Genericity, Containers Polymorphism Code that works for many types. Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson)
More informationItem 4: Extensible Templates: Via Inheritance or Traits?
ITEM1_11new.fm Page 1 Tuesday, November 27, 2001 12:49 PM Item 4: Extensible Templates: Via Inheritance or Traits?. ITEM 4: EXTENSIBLE TEMPLATES: VIA INHERITANCE OR TRAITS? DIFFICULTY: 7 This Item reviews
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 informationConcepts for the C++0x Standard Library: Iterators
Concepts for the C++0x Standard Library: Iterators Douglas Gregor, Jeremiah Willcock, and Andrew Lumsdaine Open Systems Laboratory Indiana University Bloomington, IN 47405 {dgregor, jewillco, lums@cs.indiana.edu
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 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 informationIterator Concepts for the C++0x Standard Library
Iterator Concepts for the C++0x Standard Library Douglas Gregor, Jeremy Siek and Andrew Lumsdaine dgregor@osl.iu.edu, jeremy.siek@colorado.edu, lums@osl.iu.edu Document number: N2500=08-0010 Revises document
More informationIterator Facade. Table of Contents. Overview. Usage. Iterator Core Access operator[] operator-> Reference
Iterator Facade Author: Contact: Organization: David Abrahams, Jeremy Siek, Thomas Witt dave@boost-consulting.com, jsiek@osl.iu.edu, witt@ive.uni-hannover.de Boost Consulting, Indiana University Open Systems
More informationOperating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst
Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively
More informationFundamentals of Type-Dependent Code Reuse in C++ Mark Isaacson
Fundamentals of Type-Dependent Code Reuse in C++ Mark Isaacson Roadmap Reusing an implementation Selecting between implementations Opt-in functions A Beginning assert(max(3, 5) == 5); assert(max("abc"s,
More informationG Programming Languages Spring 2010 Lecture 11. Robert Soulé, New York University
G22.2110-001 Programming Languages Spring 2010 Lecture 11 Robert Soulé, New York University 1 Review Last week Constructors, Destructors, and Assignment Operators Classes and Functions: Design and Declaration
More informationC++ Important Questions with Answers
1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children
More informationStarting to Program in C++ (Basics & I/O)
Copyright by Bruce A. Draper. 2017, All Rights Reserved. Starting to Program in C++ (Basics & I/O) On Tuesday of this week, we started learning C++ by example. We gave you both the Complex class code and
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 informationD Programming Language
Group 14 Muazam Ali Anil Ozdemir D Programming Language Introduction and Why D? It doesn t come with a religion this is written somewhere along the overview of D programming language. If you actually take
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 informationConcepts for the C++0x Standard Library: Iterators (Revision 2)
Concepts for the C++0x Standard Library: Iterators (Revision 2) Douglas Gregor, Jeremy Siek and Andrew Lumsdaine Open Systems Laboratory Indiana University Bloomington, IN 47405 dgregor@osl.iu.edu, siek@colorado.edu,
More informationPairing off iterators
Pairing off iterators Anthony Williams 8th May 2002 1 Introduction Recently, a colleague approached me with an interesting problem; he had two containers with corresponding elements, so the n-th entry
More informationAN OVERVIEW OF C++ 1
AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function
More informationLecture Topics. Administrivia
ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality
More informationPage 1. Today. Last Time. Is the assembly code right? Is the assembly code right? Which compiler is right? Compiler requirements CPP Volatile
Last Time Today Compiler requirements CPP Volatile Advanced C What C programs mean int my_loop (int base) { int index, count = 0; for (index = base; index < (base+10); index++) count++; urn count; my_loop:
More informationFall 2017 CISC/CMPE320 9/27/2017
Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader
More informationCOSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14
COSC 2P91 Introduction Part Deux Week 1b Brock University Brock University (Week 1b) Introduction Part Deux 1 / 14 Source Files Like most other compiled languages, we ll be dealing with a few different
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationCSE 374 Programming Concepts & Tools
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 8 C: Miscellanea Control, Declarations, Preprocessor, printf/scanf 1 The story so far The low-level execution model of a process (one
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 informationWeek 7. Statically-typed OO languages: C++ Closer look at subtyping
C++ & Subtyping Week 7 Statically-typed OO languages: C++ Closer look at subtyping Why talk about C++? C++ is an OO extension of C Efficiency and flexibility from C OO program organization from Simula
More informationInheritance: Develop solutions by abstracting real-world object and their interaction into code to develop software solutions. Layering: Organization
Final Exam Overview: Monday, 3pm-6pm, in WLH 2005 First pages: Quiz question - No quiz of week 2 - No bit manipulation (shifting and masking) - Quizzes: week 4, 6, 8, 10 One page on C++ language features
More informationG52CPP C++ Programming Lecture 9
G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationIntroduction to C++ with content from
Introduction to C++ with content from www.cplusplus.com 2 Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup
More informationSeptember 10,
September 10, 2013 1 Bjarne Stroustrup, AT&T Bell Labs, early 80s cfront original C++ to C translator Difficult to debug Potentially inefficient Many native compilers exist today C++ is mostly upward compatible
More information1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8
Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(
More informationOperator overloading
1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The
More informationThe Design Process. General Development Issues. C/C++ and OO Rules of Thumb. Home
A l l e n I. H o l u b & A s s o c i a t e s Home C/C++ and OO Rules of Thumb The following list is essentially the table of contents for my book Enough Rope to Shoot Yourself in the Foot (McGraw-Hill,
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 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 informationIntroduction to C++ Part II. Søren Debois. Department of Theoretical Computer Science IT University of Copenhagen. September 12th, 2005
Introduction to C++ Part II Søren Debois Department of Theoretical Computer Science IT University of Copenhagen September 12th, 2005 Søren Debois (Theory, ITU) Introduction to C++ September 12th, 2005
More informationType Inference auto for Note: Note:
Type Inference C++11 provides mechanisms for type inference which make the compiler deduce the types of expressions. I m starting the book with type inference because it can make your code more concise
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 informationImportant From Last Time
Important From Last Time Embedded C Pros and cons Macros and how to avoid them Intrinsics Interrupt syntax Inline assembly Today Advanced C What C programs mean How to create C programs that mean nothing
More informationNew Iterator Concepts
New Iterator Concepts Author: David Abrahams, Jeremy Siek, Thomas Witt Contact: dave@boost-consulting.com, jsiek@osl.iu.edu, witt@styleadvisor.com Organization: Boost Consulting, Indiana University Open
More informationPage 1. Today. Important From Last Time. Is the assembly code right? Is the assembly code right? Which compiler is right?
Important From Last Time Today Embedded C Pros and cons Macros and how to avoid them Intrinsics Interrupt syntax Inline assembly Advanced C What C programs mean How to create C programs that mean nothing
More informationLectures 5-6: Introduction to C
Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most
More informationCS-XXX: Graduate Programming Languages. Lecture 9 Simply Typed Lambda Calculus. Dan Grossman 2012
CS-XXX: Graduate Programming Languages Lecture 9 Simply Typed Lambda Calculus Dan Grossman 2012 Types Major new topic worthy of several lectures: Type systems Continue to use (CBV) Lambda Caluclus as our
More informationIncreases Program Structure which results in greater reliability. Polymorphism
UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the
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 informationANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013
ANSI C Data Analysis in Geophysics Demián D. Gómez November 2013 ANSI C Standards published by the American National Standards Institute (1983-1989). Initially developed by Dennis Ritchie between 1969
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 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 informationImportant From Last Time
Important From Last Time Embedded C Ø Pros and cons Macros and how to avoid them Intrinsics Interrupt syntax Inline assembly Today Advanced C What C programs mean How to create C programs that mean nothing
More informationThe pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s
Session 2 - Classes in C++ Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) A C++ source file may contain: include directives #include
More informationLecture 8. Exceptions, Constructor, Templates TDDD86: DALP. Content. Contents Exceptions
Lecture 8 Exceptions, Constructor, Templates TDDD86: DALP Utskriftsversion av Lecture in Data Structures, Algorithms and Programming Paradigms 19th September 2017 Ahmed Rezine, IDA, Linköping University
More informationIntroduction. Programming in C++ Pointers and arrays. Pointers in C and C++ Session 5 - Pointers and Arrays Iterators
Session 5 - Pointers and Arrays Iterators Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Introduction Pointers and arrays: vestiges
More informationIntroduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language
Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup starting in 1979 based on C Introduction to C++ also
More informationC++: Overview and Features
C++: Overview and Features Richard Newman r.newman@rdg.ac.uk Room CS127 2003-12-11 Programming & Design, 2003 1 Introduction You have: used streams seen how classes are used seen some C++ code Today: good
More informationMultimedia-Programmierung Übung 3
Multimedia-Programmierung Übung 3 Ludwig-Maximilians-Universität München Sommersemester 2016 Ludwig-Maximilians-Universität München Multimedia-Programmierung 1-1 Today Ludwig-Maximilians-Universität München
More informationECE 3574: Dynamic Polymorphism using Inheritance
1 ECE 3574: Dynamic Polymorphism using Inheritance Changwoo Min 2 Administrivia Survey on class will be out tonight or tomorrow night Please, let me share your idea to improve the class! 3 Meeting 10:
More informationCS11 Advanced C++ Spring 2018 Lecture 2
CS11 Advanced C++ Spring 2018 Lecture 2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector template working It is still missing some critical functionality Iterators are
More informationTDDD38 Advanced Programming in C++
LINKÖPING UNIVERSITY Department of Computer and Information Science Software and Systems Eric Elfving 2018-04-05 Computer examination in TDDD38 Advanced Programming in C++ Date 2018-04-05 Time 08-13 Department
More informationcs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.
cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure
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 10: building large projects, beginning C++, C++ and structs
CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 10:
More informationC#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations
, 1 C#.Net VT 2009 Course Contents C# 6 hp approx. BizTalk 1,5 hp approx. No exam, but laborations Course contents Architecture Visual Studio Syntax Classes Forms Class Libraries Inheritance Other C# essentials
More informationI m sure you have been annoyed at least once by having to type out types like this:
Type Inference The first thing I m going to talk about is type inference. C++11 provides mechanisms which make the compiler deduce the types of expressions. These features allow you to make your code more
More information1c) (iv) and (v) OR (v) only (hindsight showed that the question was more ambiguous than intended)
Answers to 2008/2009 G52CFJ exam Below are the answers to last year s exam, so that you can check how you did. In many cases I have given an example answer and an idea of what elements we would look for.
More informationTradeoffs. CSE 505: Programming Languages. Lecture 15 Subtyping. Where shall we add useful completeness? Where shall we add completeness?
Tradeoffs CSE 505: Programming Languages Lecture 15 Subtyping Zach Tatlock Autumn 2017 Desirable type system properties (desiderata): soundness - exclude all programs that get stuck completeness - include
More informationQUIZ Friends class Y;
QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 08 Constants and Inline Functions Welcome to module 6 of Programming
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 informationG52CPP C++ Programming Lecture 7. Dr Jason Atkin
G52CPP C++ Programming Lecture 7 Dr Jason Atkin 1 This lecture classes (and C++ structs) Member functions inline functions 2 Last lecture: predict the sizes 3 #pragma pack(1) #include struct A
More information3. Simple Types, Variables, and Constants
3. Simple Types, Variables, and Constants This section of the lectures will look at simple containers in which you can storing single values in the programming language C++. You might find it interesting
More informationMajor Differences between Java and C++ Programming in C++ Multiple Inheritance
Programming in C++ Session 7 - Multiple Inheritance Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Major Differences between Java
More informationWeek 5, continued. This is CS50. Harvard University. Fall Cheng Gong
This is CS50. Harvard University. Fall 2014. Cheng Gong Table of Contents News... 1 Buffer Overflow... 1 Malloc... 6 Linked Lists... 7 Searching... 13 Inserting... 16 Removing... 19 News Good news everyone!
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 informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we
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 informationprintf( Please enter another number: ); scanf( %d, &num2);
CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful
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 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 informationA Generic Non-intrusive Smart Pointer Implementation
A Generic Non-intrusive Smart Pointer Implementation Anthony Williams 13th March 2001 1 Background I started writing an article about resource management using Resource Acquisition Is Initialisation (RAII),
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 informationPage 1. Stuff. Last Time. Today. Safety-Critical Systems MISRA-C. Terminology. Interrupts Inline assembly Intrinsics
Stuff Last Time Homework due next week Lab due two weeks from today Questions? Interrupts Inline assembly Intrinsics Today Safety-Critical Systems MISRA-C Subset of C language for critical systems System
More informationContract Programming For C++0x
Contract Programming For C++0x WG21/N1800 and J16/05-0060 Lawrence Crowl and Thorsten Ottosen lawrence.crowl@sun.com and nesotto@cs.aau.dk 2005-04-27 Overview This is an annotated version of the presentation
More informationWhy use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++
Session 6 - Inheritance in C++ The most important slide of the lecture Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Why use inheritance?
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 informationC++ Programming Lecture 7 Software Engineering Group
C++ Programming Lecture 7 Software Engineering Group Philipp D. Schubert Contents 1. Template metaprogramming 2. Variadic template arguments 3. Smart pointer Template metaprogramming Template metaprogramming
More informationThe list abstract data type defined a number of operations that all list-like objects ought to implement:
Chapter 7 Polymorphism Previously, we developed two data structures that implemented the list abstract data type: linked lists and array lists. However, these implementations were unsatisfying along two
More informationIntroduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms
Introduction to Linked Lists Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Lecture Slides Friday, September 25, 2009 Glenn G. Chappell Department of Computer Science
More informationCOMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016
COMP-202: Foundations of Programming Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016 Announcements Final is scheduled for Apr 21, 2pm 5pm GYM FIELD HOUSE Rows 1-21 Please submit course evaluations!
More informationProgramming Languages. Streams Wrapup, Memoization, Type Systems, and Some Monty Python
Programming Languages Streams Wrapup, Memoization, Type Systems, and Some Monty Python Quick Review of Constructing Streams Usually two ways to construct a stream. Method 1: Use a function that takes a(n)
More informationTime : 3 hours. Full Marks : 75. Own words as far as practicable. The questions are of equal value. Answer any five questions.
XEV (H-3) BCA (6) 2 0 1 0 Time : 3 hours Full Marks : 75 Candidates are required to give their answers in their Own words as far as practicable. The questions are of equal value. Answer any five questions.
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 informationC++ Inheritance and Encapsulation
C++ Inheritance and Encapsulation Private and Protected members Inheritance Type Public Inheritance Private Inheritance Protected Inheritance Special method inheritance 1 Private Members Private members
More informationQUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?
QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The
More information