C++ Modern and Lucid C++ for Professional Programmers
|
|
- Vivian Bradley
- 5 years ago
- Views:
Transcription
1 Informatik C++ Modern and Lucid C++ for Professional Programmers part 9 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2015
2 Functors and Parameterizing STL Functors, Lambdas, Standard Functors, std::function<>
3 Function Objects struct donothingfunctor{ We can overload the function call operator as member of a class -> Functor class, instance: functor object ret operator()(params) {... ; void operator()()const{ Two pairs of parentheses required! usually const-member, unless changing member variables of the function object Member variables can keep memory! donothingfunctor{(); construct and call 3
4 Example: Functor with memory #include <iostream> #include <algorithm> #include <vector> struct averager { void operator()(double d) { accumulator += d; ++counter; double sum() const { return accumulator; double count() const { return counter; double average() const { return sum()/count(); private: double accumulator{; unsigned counter{; ; int main(){ std::vector<double> v{7,4,1,3,5,3.3,4.7; auto const res=for_each(v.begin(),v.end(),averager{); std::cout << "sum = " << res.sum() << '\n' << "count = " << res.count() << '\n' << "average = "<< res.average() << '\n'; res is resulting averager object 4
5 Function/Functor Terminology Function: unary function, binary function,... Operator function: unary operator, binary operator Functor: unary functor, binary functor Predicate: function/functor with bool result unary predicate: a property of its argument binary predicate: compare two arguments 5
6 Generator Functors std::vector<int> v; int x{; // memory for lambda below generate_n(std::back_inserter(v),10,[&x]{ ); ++x; return x*x; generate() algorithm requires function with "memory" if not all values should be the same (nullary function, no parameters) Lambda requires variable captured by & or mutable lambda class make_squares{ int x{; public: int operator()() { ++x; return x*x; ; //... generate(v.begin(),v.end(),make_squares{); 6
7 Lambda Function Syntax Defining Inline Functions definition auto const g=[](char c)->char{return std::toupper(c);; g('a'); call auto const for function variable from Lambda is used to call function [] introduces Lambda function can contain captures, e.g., [=] or [&] to access variables (parameters), as with other functions, but can be auto -> trailing return type, if cannot be deduced (not needed) body block with statements 7
8 Recap Lambda Rules [capture](parameters)mutableopt->return_type{body Capture: [=], [&], [var=value] Parameters: auto p1, int p2, auto mutable: allow changing capture variables in body Return_type: typically deduced automatically Body: return statement(s) provide return type implicitly 8
9 Lambda Captures [capture](parameters)mutableopt->return_type{body Capture: [=] - default implicit capture variables used in body by value [&] - default capture variable used in body by reference [var=value] - introduce new capture variable with value combinations of specific captures with a default [=,&out] - capture all by copy, but out by reference [&,=x] - capture all by reference, but x by copy/value Guideline: always capture variables explicitly 9
10 Lambda Special Case: mutable generate_n(std::back_inserter(v),10,[x=0]() mutable { return ++x, x*x; // mutable allows change allow changing x ); introduce new capture variable x variables captured by copy (=) are const within the lambda, unless... the lambda is marked mutable, and the lambda gets its own copy of the variable, or the lambda defines its capture with an initializer lambdas are mapped internally to functors 10
11 Lambdas are functors A C++ compiler internally maps lambdas to functor objects with an unaccessible/hidden class name [&x]{ ++x; return x*x; struct _unknown_generator_name_{ _unknown_generator_name_(int &x):x{x{ auto operator()() const { ++x; return x*x; private: int &x; ; [](char c)->char{ return std::toupper(c); struct _unknown_converter_name_ { auto operator()(char c) const ->char{ return std::toupper(c); ; 11
12 Lambdas in Member Functions this-> struct DemoLambdaMemberVariables { int x{; std::vector<int> demoaccessingmemberfromlambda() { std::vector<int> v; generate_n(back_inserter(v),10,[=] { return ++x, x*x; // member x can be changed ); return v; ; capture this by copy Captured member variables are always captured by reference, even if the default is [=] Reason: this is a pointer (reference) and if copied, member variables are referred from it this can not be captured by reference 12
13 Standard Functor template Classes transform(v.begin(),v.end(),v.begin(),[](int x){return -x;); transform(v.begin(),v.end(),v.begin(),std::negate<int>{); Lambdas make applying transform etc. quite easy However, if there is only a simple expression used, there is a chance for reuse of the standard library's functor classes for almost all operators also relational operators, e.g., sorting in descending order sort(v.begin(),v.end(),std::greater<>{); parameter type deduced 13
14 standard functor classes #include <functional> binary arithmetic and logical plus<> (+) minus<> (-) divides<> (/) multiplies<> (*) modulus<> (%) logical_and<> (&&) logical_or<> ( ) transform(v.begin(),v.end(),v.begin(), v.begin(),std::multiplies<>{); unary negate<> (-) logical_not<> (!) binary comparison less<> (<) less_equal<> (<=) equal_to<> (==) greater_equal<> (>=) greater<> (>) not_equal_to<> (!=) 14
15 Parameterize Associative Containers std::set<int,std::greater<>> reverse_int_set{; Associative containers allow an additional template argument for the comparison operation it must be a functor class giving a binary predicate predicate must be irreflexive and transitive Own functors can provide special sort order, e.g., case-less comparison of strings caution: requirements for sorting must be fulfilled, e.g. >= (std::greater_equal) is not allowed (is reflexive!) 15
16 Example: set<string> for dictionary #include <set> #include <functional> #include <algorithm> #include <cctype> #include <iterator> #include <iostream> struct caseless{ using string=std::string; bool operator()(string const &l, string const &r){ return std::lexicographical_compare( l.begin(),l.end(),r.begin(),r.end(), [](char l,char r){ return std::tolower(l) < std::tolower(r); ); ; int main(){ using std::string; using caseless_set=std::multiset<string,caseless>; using in=std::istream_iterator<string>; caseless_set wlist{in{std::cin,in{; std::ostream_iterator<string> out{std::cout,"\n"; copy(wlist.begin(),wlist.end(),out); binary predicate strings as ranges lambda as binary predicate on char pass predicate functor as template argument 16
17 How to keep functors around? In situations where you not only provide a functor but want to take a function or functor as parameter, e.g., in a constructor and later apply it, what should be the type of the (member) variable and the parameter? foo(double f(double)); doesn't work with functors neither does your specific functor type for others 2 options: template typename parameter (later) std::function<double(double)> 17
18 std::function<signature> std::function<bool(int)> apredicate{; Universal function holder can store functions, functor instances or lambdas signature must be compatible with the SIGNATURE function template argument can be reassigned or emptied can be empty -> might need to check if (apredicate) { // implicit bool conversion: is valid? cout << "pred(42) is " << apredicate(42) << '\n'; else { cout << "empty function\n"; 18
19 #include <functional> #include <iostream> Example: using std::function<> void apply_and_print(std::ostream& cout, std::function<bool(int)> apredicate) { if (apredicate) { // implicit bool conversion cout << "pred(42) is " << apredicate(42) << '\n'; else { cout << "empty function holder\n"; function parameter check for validity call operator() of int main(){ using std::cout; cout << std::boolalpha; // true/false in output std::function<bool(int)> apredicate{; apply_and_print(cout,apredicate); apredicate = [](int i){return i%2;; apply_and_print(cout,apredicate); apredicate = std::not1(apredicate); apply_and_print(cout,apredicate); apredicate = nullptr; apply_and_print(cout,apredicate); default is empty -> invalid to call std::not1() creates logically negated unary predicate functor nullptr assignment makes function empty 19
20 std::function with member functions #include <functional> #include <iostream> member function to wrap struct X { int calc(int i) const { return x*i; private: int x{7; ; make variable const to avoid invalid function objects (general rule!) int main(){ std::function<int (X const &,int)> const f{&x::calc; X const anx{; std::cout << f(anx,6); must pass object as this argument explicitly member function pointer must specify & address-of operator to member 20
21 What is a member-(function) pointer? It is possible to refer to individual class members using "pointer-to-members" e.g., to handle different members of the same type by the same function syntax of the type: type Class::* varname; initialize such a value by: &Class::member This extends to "pointer-to-member-functions" syntax: resulttype (Class::*)(params) 21
22 Example Pointer to Members.* struct X { void foo() const { std::cout << a << " foo\n"; void bar() const { std::cout << b << " bar\n"; int a; int b; ; must match m-f signature including const and parameters void doit(void (X::*mfunc)() const, X const &x){ (x.*mfunc)(); // parenthesis needed void change(int X::*memvar, X& x, int val){ use operator.* for member function pointer () required - precedence x.*memvar = val; use operator.* for pointer to member access int main(){ X x{1,2; doit(&x::foo,x); doit(&x::bar,x); change(&x::a,x,42); change(&x::b,x,43); doit(&x::foo,x); doit(&x::bar,x); 1 foo 2 bar 42 foo 43 bar 22
23 std::function calling member function auto g=std::function<void(x const&, int)>{&x::foo; X x{42,43; g(x,1); // calls -> x.foo(1) x.bar(2); struct X { void foo(int) const ; void bar(int) const ; int a; int b; ; std::function for a member function makes passing the this object explicit Here you see, that what is left of the. operator is actually passed to the member function as an argument 23
24 Creating your own iterator types #include <iterator> algorithms are parameterized by functors but also by iterators You can create or wrap iterators using boost::iterators library #include <boost/iterator/counting_iterator.hpp> #include <boost/iterator/filter_iterator.hpp> #include <boost/iterator/transform_iterator.hpp> Or you can implement your own iterators (see C++ advanced) with the help of <boost/operators.hpp> 24
25 Recap: Iterator Categories Different algorithms require different strengths of iterators InputIterator - read sequence once OutputIterator - write results, without designating an end ForwardIterator - read/write sequence, multiple passes BidirectionalIterator - read/write sequence, back-forth RandomAccessIterator - read/write/indexed sequence more versatile iterator can be used for more efficient algorithm Iterator's capabilities can be determined at compile time 25
26 Boost Iterator Library #include <boost/iterator/counting_iterator.hpp> #include <boost/iterator/filter_iterator.hpp> #include <boost/iterator/transform_iterator.hpp> Several pre-defined adapters with factory functions, for example counting filtering transforming See also 26
27 Example: using Boost Iterator struct odd{ bool operator()(int n)const{return n%2; ; int main(){ using counter=boost::counting_iterator<int>; std::vector<int> v(counter{1,counter{11); std::ostream_iterator<int> out{std::cout,", "; copy(v.begin(),v.end(),out); std::cout << '\n'; using boost::make_filter_iterator; copy(make_filter_iterator(odd{,v.begin(),v.end()), make_filter_iterator(odd{,v.end(),v.end()), out); std::cout << '\n'; using boost::make_transform_iterator; auto square=[](auto x){ return x*x;; copy(make_transform_iterator(v.begin(),square), make_transform_iterator(v.end(),square), out); functor for filtering counting iterator filter iterator, only odd values provided transform iterator applies function/functor/ lambda for each value 27
28 Summary Parameterize the standard library through Functors Lambdas Iterators construct your own with boost::iterator library Store and pass functions / function objects in std::function<> 28
SFU CMPT Topic: Function Objects
SFU CMPT-212 2008-1 1 Topic: Function Objects SFU CMPT-212 2008-1 Topic: Function Objects Ján Maňuch E-mail: jmanuch@sfu.ca Friday 14 th March, 2008 SFU CMPT-212 2008-1 2 Topic: Function Objects Function
More informationCOMP6771 Advanced C++ Programming
1........ COMP6771 Advanced C++ Programming Week 4 Part Three: Function Objects and 2016 www.cse.unsw.edu.au/ cs6771 2........ Converting Class Types to bool Convenient to use a class object as bool to
More informationC++1z: Concepts-Lite !!! !!! !!!! Advanced Developer Conference C slides:
C++1z: Concepts-Lite Advanced Developer Conference C++ 2014 slides: http://wiki.hsr.ch/petersommerlad/ Prof. Peter Sommerlad Director IFS Institute for Software Peter Sommerlad peter.sommerlad@hsr.ch Credo:
More informationC++ Modern and Lucid C++ for Professional Programmers
Informatik C++ Modern and Lucid C++ for Professional Programmers Part 1 Self-study for Introduction to C++ Prof. Peter Sommerlad Director IFS Institute for Software Rapperswil, HS 2017 Thomas Corbat Additional
More informationFunctions. Ali Malik
Functions Ali Malik malikali@stanford.edu Game Plan Recap Operator Overloading Functions Lambdas Announcements Recap Classes - Issues C++ doesn t know how to use operators on types defined by us: We can
More informationC++ Modern and Lucid C++ for Professional Programmers
Informatik C++ Modern and Lucid C++ for Professional Programmers part 13 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2015 Inheritance and dynamic Polymorphism base classes,
More informationP0984R0 - All (*)()-Pointers Replaced by Ideal Lambdas Functions Objects Obsoleted by Lambdas
P0984R0 - All (*)()-Pointers Replaced by Ideal Lambdas Functions Objects Obsoleted by Lambdas Peter Sommerlad 2018-04-01 Document Number: P0984R0 Date: 2018-04-01 Project: Programming Language C++ Audience:
More informationFunctions. Ali Malik
Functions Ali Malik malikali@stanford.edu Game Plan Recap Operator Overloading Functions Lambdas Announcements Recap Classes - Issues C++ doesn t know how to use operators on types defined by us An algorithm
More informationLambda functions. Zoltán Porkoláb: C++11/14 1
Lambda functions Terminology How it is compiled Capture by value and reference Mutable lambdas Use of this Init capture and generalized lambdas in C++14 Constexpr lambda and capture *this and C++17 Zoltán
More informationC++ for numerical computing - part 2
C++ for numerical computing - part 2 Rupert Nash r.nash@epcc.ed.ac.uk 1 / 36 Recap 2 / 36 Iterators std::vector data = GetData(n); // C style iteration - fully explicit for (auto i=0; i!= n; ++i)
More informationThe STL <functional> Library
CS106L Fall 2007 Handout #20 November 28, 2007 The STL Library Introduction Up to this point, all of the programs you have encountered in CS106 have used immutable functions to create and
More informationModern and Lucid C++ Advanced for Professional Programmers. Part 1 C Plus Plus Recap. Department I - C Plus Plus
Department I - C Plus Plus Modern and Lucid C++ Advanced for Professional Programmers Part 1 C Plus Plus Recap Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 23.02.2018 HS2018 Values vs. References
More informationObject-Oriented Programming
- oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne
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 informationOverload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018
Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 1 Introduction Definition of Function Overloading Determining which Overload to call How Overload Resolution Works Standard Conversion Sequences
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationCSCI 104 Templates. Mark Redekopp David Kempe
CSCI 104 Templates Mark Redekopp David Kempe Overview C++ Templates allow alternate versions of the same code to be generated for various data types 2 FUNCTION TEMPLATES 3 How To's Example reproduced from:
More informationAbstraction and Encapsulation. Benefits of Abstraction & Encapsulation. Concrete Types. Using Typedefs to streamline classes.
Classes II: Type Conversion,, For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Abstraction and Encapsulation Abstraction: Separation of interface from
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More information2 ADT Programming User-defined abstract data types
Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct
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 informationOutline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor
Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened
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 informationFunctors. Cristian Cibils
Functors Cristian Cibils (ccibils@stanford.edu) Administrivia You should have Evil Hangman feedback on paperless. If it is there, you received credit Functors Let's say that we needed to find the number
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 informationCSCI 104 Templates. Mark Redekopp David Kempe
1 CSCI 104 Templates Mark Redekopp David Kempe 2 Overview C++ Templates allow alternate versions of the same code to be generated for various data types FUNCTION TEMPLATES 3 4 How To's Example reproduced
More informationLecture 2 Polymorphism, Traits, Policies, and Inheritance
Lecture 2 Polymorphism, Traits, Policies, and Inheritance Kenny Erleben Department of Computer Science University of Copenhagen c K. Erleben, May 4, 2006 p. 1/36 Polymorphism 1 Traditional, define abstract
More informationTokens, Expressions and Control Structures
3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type
More informationOverload Resolution. Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019
Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019 1 Introduction Prologue Definition of Function Overloading Determining which Overload to call How Works Standard Conversion Sequences Examples
More informationCHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object
CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,
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 informationCS 247: Software Engineering Principles. C++ Templates. Reading: Eckel, Vol. 2 Ch. 5 Templates in Depth. U Waterloo CS247 (Spring 2017) p.
CS 247: Software Engineering Principles C++ Templates Reading: Eckel, Vol. 2 Ch. 5 Templates in Depth U Waterloo CS247 (Spring 2017) p.1/16 Overloaded Functions Problem: Code in overloaded functions whose
More informationFunctional Programming in C++
Functional Programming in C++ David Letscher Saint Louis University Programming Languages Letscher (SLU) Functional Programming in C++ Prog Lang 1 / 17 What is needed to incorporate functional programming?
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 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 informationProgram construction in C++ for Scientific Computing
1 (26) School of Engineering Sciences Program construction in C++ for Scientific Computing 2 (26) Outline 1 2 3 4 5 6 3 (26) Our Point class is a model for the vector space R 2. In this space, operations
More informationElevate your Code to Modern C++ with Automated Tooling. Peter Sommerlad
Elevate your Code to Modern C++ with Automated Tooling Peter Sommerlad Simple C++ Less Code == More Software Know your language and its (modern) idioms Don t be afraid of STL or templates Start small.
More informationOverloaded Operators, Functions, and Students
, Functions, and Students Division of Mathematics and Computer Science Maryville College Outline Overloading Symbols 1 Overloading Symbols 2 3 Symbol Overloading Overloading Symbols A symbol is overloaded
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 informationC++11 and Compiler Update
C++11 and Compiler Update John JT Thomas Sr. Director Application Developer Products About this Session A Brief History Features of C++11 you should be using now Questions 2 Bjarne Stroustrup C with 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 information10. Functions (Part 2)
10.1 Overloaded functions 10. Functions (Part 2) In C++, two different functions can have the same name if their parameters are different; either because they have a different number of parameters, or
More informationCSCI-1200 Data Structures Fall 2009 Lecture 20 Hash Tables, Part II
Review from Lecture 19 CSCI-1200 Data Structures Fall 2009 Lecture 20 Hash Tables, Part II Operators as non-member functions, as member functions, and as friend functions. A hash table is a table implementation
More informationIV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard
IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two
More informationOutline. 1 About the course
Outline EDAF50 C++ Programming 1. Introduction 1 About the course Sven Gestegård Robertz Computer Science, LTH 2018 2 Presentation of C++ History Introduction Data types and variables 1. Introduction 2/1
More informationCSCI-1200 Data Structures Fall 2018 Lecture 21 Hash Tables, part 1
Review from Lecture 20 CSCI-1200 Data Structures Fall 2018 Lecture 21 Hash Tables, part 1 Finishing binary search trees & the ds set class Operators as non-member functions, as member functions, and as
More informationPart XI. Algorithms and Templates. Philip Blakely (LSC) C++ Introduction 314 / 370
Part XI Algorithms and Templates Philip Blakely (LSC) C++ Introduction 314 / 370 STL Algorithms Outline 44 STL Algorithms 45 Templates 46 Summing an array 47 Templated classes Philip Blakely (LSC) C++
More informationValue categories. PRvalues. Lvalues
Value categories v5 Every C++14 expression belongs to exactly one of the following classifications, known as value categories: lvalue, xvalue, prvalue. There's an overlap between these, so a higher level
More informationAdvanced Systems Programming
Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short
More informationAn introduction to C++ template programming
An introduction to C++ template programming Hayo Thielecke University of Birmingham http://www.cs.bham.ac.uk/~hxt March 2015 Templates and parametric polymorphism Template parameters Member functions of
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 informationCSCI-1200 Data Structures Fall 2017 Lecture 23 Functors & Hash Tables, part II
CSCI-1200 Data Structures Fall 2017 Lecture 23 Functors & Hash Tables, part II Review from Lecture 22 A Heap as a Vector Building a Heap Heap Sort the single most important data structure known to mankind
More informationOBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe
OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++
More informationTemplates. Zoltán Porkoláb: C++11/14 1
Templates From macros to templates Parameter deduction, instantiation,specialization Class templates, partial specialization Explicit instantiation Dependent types Scope resolution, lookup Mixins CRTP
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 informationCHAPTER 4 FUNCTIONS. 4.1 Introduction
CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main
More informationMODERN AND LUCID C++ ADVANCED
Informatik MODERN AND LUCID C++ ADVANCED for Professional Programmers Prof. Peter Sommerlad Thomas Corbat Director of IFS Research Assistant Rapperswil, FS 2016 LIBRARY API/ABI DESIGN PIMPL IDIOM HOURGLASS
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 informationIntroduction to Programming
Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines
More informationMODULE 37 --THE STL-- ALGORITHM PART V
MODULE 37 --THE STL-- ALGORITHM PART V My Training Period: hours Note: Compiled using Microsoft Visual C++.Net, win32 empty console mode application. g++ compilation example is given at the end of this
More informationThe STL <functional> Library
CS106L Spring 2009 Handout #28 May 21, 2009 The STL Library Introduction In the previous handout, we explored functors, objects that implement the operator () function, and demonstrated how
More informationAppendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.
A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators
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 informationReview. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?
Review Describe pass-by-value and pass-by-reference Why do we use pass-by-reference? What does the term calling object refer to? What is a const member function? What is a const object? How do we initialize
More informationTDDD38 - Advanced programming in C++
TDDD38 - Advanced programming in C++ Templates III Christoffer Holm Department of Computer and information science 1 Dependent Names 2 More on Templates 3 SFINAE 1 Dependent Names 2 More on Templates 3
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 informationModule Operator Overloading and Type Conversion. Table of Contents
1 Module - 33 Operator Overloading and Type Conversion Table of Contents 1. Introduction 2. Operator Overloading 3. this pointer 4. Overloading Unary Operators 5. Overloading Binary Operators 6. Overloading
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationI BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++
No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)
More informationBasic Types, Variables, Literals, Constants
Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic
More informationCS 376b Computer Vision
CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves
More informationA Parallel Algorithms Library N3724
A Parallel Algorithms Library N3724 Jared Hoberock Jaydeep Marathe Michael Garland Olivier Giroux Vinod Grover {jhoberock, jmarathe, mgarland, ogiroux, vgrover}@nvidia.com Artur Laksberg Herb Sutter {arturl,
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 informationThe Ada Standard Generic Library (SGL)
The Ada Standard Generic Library (SGL) Alexander V. Konstantinou Computer Science Graduate Seminar 4/24/96 1 Presentation Overview Introduction (S{T G}L) The C++ Standard Template Library (STL) Ada 95
More informationIII. Classes (Chap. 3)
III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,
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 informationTutorial 7. Y. Bernat. Object Oriented Programming 2, Spring Y. Bernat Tutorial 7
Tutorial 7 Y. Bernat Object Oriented Programming 2, Spring 2016 Exercise 4 STL Outline Part I Today's Topics 1 Exercise 4 2 STL Containers - continue Lambda functions Algorithms Exercise 4 STL Exercise
More informationCpt S 122 Data Structures. Templates
Cpt S 122 Data Structures Templates Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Function Template Function-template and function-template
More informationCOMP322 - Introduction to C++ Lecture 01 - Introduction
COMP322 - Introduction to C++ Lecture 01 - Introduction Robert D. Vincent School of Computer Science 6 January 2010 What this course is Crash course in C++ Only 14 lectures Single-credit course What this
More informationCOMP6771 Advanced C++ Programming
1.. COMP6771 Advanced C++ Programming Week 6 Part One: Function Templates 2016 www.cse.unsw.edu.au/ cs6771 2.. Constants Two notions of immutability: const: A promise not to change this value. Used primarily
More informationOperators. Lecture 3 COP 3014 Spring January 16, 2018
Operators Lecture 3 COP 3014 Spring 2018 January 16, 2018 Operators Special built-in symbols that have functionality, and work on operands operand an input to an operator Arity - how many operands an operator
More informationW3101: Programming Languages C++ Ramana Isukapalli
Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical
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 informationStructuur van Computerprogramma s 2
Structuur van Computerprogramma s 2 dr. Dirk Deridder Dirk.Deridder@vub.ac.be http://soft.vub.ac.be/ Vrije Universiteit Brussel - Faculty of Science and Bio-Engineering Sciences - Computer Science Department
More informationclass Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };
Default Arguments 1 When declaring a C++ function, you may optionally specify a default value for function parameters by listing initializations for them in the declaration: class Polynomial { public:
More informationcalling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!
Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns
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 informationIntroduction. Contents. Homogeneous interface for variant<ts...>, any and optional<t>
Document number: P0032 Date: 2015 09-24 Project: Programming Language C++, Library Evolution Working Group Reply-to: Vicente J. Botet Escriba Homogeneous interface for variant,
More informationMODULE 35 --THE STL-- ALGORITHM PART III
MODULE 35 --THE STL-- ALGORITHM PART III My Training Period: hours Note: Compiled using Microsoft Visual C++.Net, win32 empty console mode application. g++ compilation example is given at the end of this
More informationIntroduction to Programming using C++
Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know
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 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 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 informationCSCI-1200 Data Structures Fall 2015 Lecture 24 Hash Tables
CSCI-1200 Data Structures Fall 2015 Lecture 24 Hash Tables Review from Lecture 22 & 23 STL Queues & Stacks Definition of a Prioriry Queue / Binary Heap percolate_up and percolate_down A Heap as a Vector,
More informationUsing Enum Structs as Bitfields
New York C++ Developers Group July 12, 2016 Using Enum Structs as Bitfields Presentation by Jon Kalb Based on an article in Overload magazine by Anthony Williams 1 What do these have in common?! explicit
More informationFunctions and Recursion
Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function
More informationFinal exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)
Review Final exam Final exam will be 12 problems, drop any 2 Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers) 2 hours exam time, so 12 min per problem (midterm 2 had
More informationImplicit Evaluation of auto Variables and Arguments
Implicit Evaluation of auto Variables and Arguments Document number: N4035 (update of N3748) Authors: Joël Falcou University Paris XI, LRI Peter Gottschling SimuNova Herb Sutter Microsoft Date: 2013-08-30
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 informationCpt S 122 Data Structures. Introduction to C++ Part II
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
More information