Parallelism in C++ J. Daniel Garcia. Universidad Carlos III de Madrid. November 23, 2018

Size: px
Start display at page:

Download "Parallelism in C++ J. Daniel Garcia. Universidad Carlos III de Madrid. November 23, 2018"

Transcription

1 J. Daniel Garcia Universidad Carlos III de Madrid November 23, 2018 cbea J. Daniel Garcia 1/58

2 Introduction to generic programming 1 Introduction to generic programming 2 STL: Standard Template Library 3 Execution policies 4 5 More? cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 2/58

3 Introduction to generic programming What is generic programming? Approach allowing to generalize program entities. Also known as parametric polymorphism. Provides compile-time polymorphism as opposed to dynamic polymorphism from object orientation. Very good combination of flexibility and performance. Which are the entities that can be generalized? Classes (types) and functions. What can be a parameter for the generic? A type. An integral value. Example template <class T, int N> class buffer { /... / }; buffer<int,100> b1; buffer<char,20> b2; cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 3/58

4 Introduction to generic programming Templates: Defining generic types A template allows to define a data type that is parametrized by another data type. vector<double> v; vector<int> w; map<string,int> d; vector<vector<string>> x; A template requires that all definitions are visible at compile time (instead of link time). Practical effect: All definitions in headers. template <typename T> class vector { //... }; template <typename K, typename V> class map { //... }; cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 4/58

5 Introduction to generic programming A generic vector class vector.h (I) template <typename T> class vector { public: vector() ; explicit vector( int n); vector(std :: initializer_list <T> il ) ; vector(const vector &); vector & operator=(const vector &); vector(vector &&) = default; vector & operator=(vector &&) = default; T operator[](int i ) const { return vec[i ]; } T & operator[](int i ) { return vec[i ]; } //... cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 5/58

6 Introduction to generic programming A generic vector class vector.h (II) unsigned long num_elems() const { return tam; } unsigned long capacity() const { return total; } void reserve(int n); void redim(int n); void add_end(const T & x); private: unsigned long tam; unsigned long total; std :: unique_ptr<t[]> vec; }; //... cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 6/58

7 Introduction to generic programming Implementing member functions vector.h (III) template <typename T> vector<t>::vector() : tam{0}, total {0}, vec{nullptr} {} template <typename T> vector<t>::vector(int n) : tam{(n>0)?static_cast<unsigned long>(n):0}, total {tam}, vec{make_unique<t[]>(total)} {} cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 7/58

8 Introduction to generic programming Non-type template parameters A template can be defined with a parameter that is not a type but a value. template <typename T, int N> struct array { //... }; Values used in instantiation must be known at compile time. array<double,1024> v1; // OK constexpr int max = 512; array<double, max> v2; // OK int tam = 256; array<double, tam> v3; // Error cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 8/58

9 Introduction to generic programming A template for arrays array.h template <typename T, int N> struct array { T vec[n]; T & operator[](int i ) { return vec[i ]; } const T & operator[](int i ) const { return vec[i ]; } int tam() const { return N; } }; void f () { array<int,12> v; for ( int i=0;i<12;++i) { v[ i ] = 2 i ; } for ( int i=0;i<12;++i) { cout << v[ i ] << endl; } } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 9/58

10 Introduction to generic programming Function templates A template can be used to define a family of functions in a generic way. template <typename O, typename C> void print (O & os, const C & c, string sep) { for (auto & x : c) { os << x << sep; } } Template parameters are deduced at call site. void f () { vector<string> v1 {"C++", "is ", " faster ", "than", "C"}; array<double,4> v2 {1.0, 2.0, 3.0, 4.0}; print (cout, v1, " \n") ; // O >ostream, C >vector<string> print (cout, v2, ", ") ; // O >ostream, C >vector<double> } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 10/58

11 STL: Standard Template Library 1 Introduction to generic programming 2 STL: Standard Template Library 3 Execution policies 4 5 More? cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 11/58

12 STL: Standard Template Library STL: Standard Template Library Originally designed by Alexander Stepanov. Original goal: the most general, efficient and flexible representation of concepts. Represent separate concepts separately in code. Freely combine concepts as long as they make sense. Basic model: Containers: Structures storing data. Iterators: Allows traversing containers. Algorithms: Perform data manipulation independently from containers. cbea J. Daniel Garcia 12/58

13 STL: Standard Template Library Containers A container stores a sequence of objects. Sequences: Allow accessing a sequence (semi-open) of objects. vector<t,a>, deque<t,a>, list<t,a>, forward_list<t,a>, array<t,n>. Associative containers: Allow finding pairs key-value. Ordered: map<k,v,c,a>, multimap<k,v,c,a>, set<k,v,c,a>, multiset<k,v,c,a>. Unordered: unordered_map<k,v,c,a>, unordered_multimap<k,v,c,a>, unordered_set<k,v,c,a>, unordered_multiset<k,v,c,a>. Others: Adaptors and views. Adaptors: stack<t,c>, queue<t,c>, priority_queue<t,c,cmp>. Views: span<t,e>. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 13/58

14 STL: Standard Template Library Iterators An iterator generalizes the abstraction of pointer to perform indirect accesses. Many iterators satisfy the concept of InputIterator. They can advance: ++i. They can access the pointed object: x = *i. They allow for equality comparison: i == j, i!=j. Some iterators support more operations: i, i+n, i+=n, i[n], i<j,... cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 14/58

15 STL: Standard Template Library Iterators and containers All containers have an associated iterator type defined. Type iterator. vector<int>::iterator, list<double>::iterator, deque<string>::iterator,... All containers have two member functions defining their sequence. c.begin(): Iterator to the beginning of the sequence. c.end(): Iterator to one-past-the-end of the sequence. Sequences as semi-open interval [start, end). Print a list of values from container c for (auto i=c.begin(); i!=c.end(); ++i) { cout << i << endl; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 15/58

16 STL: Standard Template Library Algorithms Using iterators allows to define algorithms independently from specific containers. Find a value template <typename I, typename T> I find ( I first, I last, const T & x) { while ( first!= last && first!=x) first ++ return first ; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 16/58

17 STL: Standard Template Library Algorithms Using iterators allows to define algorithms independently from specific containers. Find a value template <typename I, typename T> I find ( I first, I last, const T & x) { while ( first!= last && first!=x) first ++ return first ; } Using find bool has(vector<int> & v, int x) { auto p = find (v.begin(), v.end(), x); return p!=v.end(); } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 16/58

18 STL: Standard Template Library Algorithms and predicates Finding with predicates template <typename I, typename P> I find_if ( I first, I last, P pred) { while ( first!= last &&!pred( first )) prim++; return first ; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 17/58

19 STL: Standard Template Library Algorithms and predicates Finding with predicates template <typename I, typename P> I find_if ( I first, I last, P pred) { while ( first!= last &&!pred( first )) prim++; return first ; } Using find vector<int> v {1,2,3,4,5,6,7,8}; auto p = find_if (v.begin(), v.end(), []( int x) { return (x%2==0) && (x%3==0); }); cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 17/58

20 STL: Standard Template Library Algorithms in STL Great variety 90 algorithms. Classification: Sequence algorithms: Modifying and non-modifying. Partitioning, sorting, binary search. Set and heap operations. Minimum and maximum operations. Numeric operations. cbea J. Daniel Garcia 18/58

21 STL: Standard Template Library Applying and operation to a sequence Applies a function object to each element in a sequence. template <typename I, typename F> F for_each(i first, I last, F f ) ; Example vector<int> v {1,2,3,4,5,6,7,8}; for_each(begin(v), end(v), []( int x) { cout << x; }) ; cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 19/58

22 STL: Standard Template Library Copying a sequence Copies a sequence into another sequence. template <typename I, typename O> O copy(i first, I last, O first2 ) ; Example vector<int> v {1,2,3,4,5,6,7,8}; vector<int> w; w.resize(8); copy(begin(v), end(v), begin(w)); // w must have enough space. vector<int> z; copy(begin(v), end(v), back_inserter(w)); // Copies by inserting. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 20/58

23 STL: Standard Template Library Transformation Transforms a sequence into another by applying an operation. template <typename I, typename O, typename F> O transform(i first, I last, O first2, F unop); template <typename I, typename O, typename F> O transform(i first1, I last1, I first2, I last2, O first3, F binop); Example vector<int> v {1,2,3,4,5,6,7,8}; vector<int> w; transform(begin(v), end(v), back_inserter(w), []( int x) {return x x}); vector<int> z; transform(begin(v), end(v), begin(w), end(w), back_inserter(z), []( int x, int y) { return x+y; }) ; cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 21/58

24 Execution policies 1 Introduction to generic programming 2 STL: Standard Template Library 3 Execution policies 4 5 More? cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 22/58

25 Execution policies Introduction An execution policy specifies the type of parallelism that is allowed in the execution of the algorithm. Sequential: No parallelism. Type: sequenced_policy. Global object: seq. Parallel: Parallel execution. Typo: parallel_policy. Global object: par. Parallel + Vector: Parallelized and vectorized. Type: parallel_unseq_policy. Global object: par_unseq. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 23/58

26 Execution policies Algorithm versions All parallel algorithms take as a first argument an execution policy. Example: sorting a vector using namespace std; vector<double> v = read_values(); sort(v.begin(), v.end()); using namespace std::experimental::parallel; sort(seq, v.begin(), v.end()); // Sequential sort(par, v.begin(), v.end()); // Parallel sort(par_unseq, v.begin(), v.end()); // Parallel + Vector cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 24/58

27 1 Introduction to generic programming 2 STL: Standard Template Library 3 Execution policies 4 5 More? cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 25/58

28 What algorithms are included? Parallel algorithms library includes most algorithms in the STL. In all cases an additional argument is added to signal the execution policy. Policy argument is always the first one. Some algorithms from the STL have been excluded. Example: accumulate. Some algorithms do not come from the STL. Example: exclusive_scan cbea J. Daniel Garcia 26/58

29 Categories of algorithms Invariant: Find out something about a sequence. Modifying: Perform modifications on a sequence. Partitioning: Support the idea of partitioning a sequence. Sorting: Sorting and support algorithms on sequences. Set operations: Apply set operations on sequences. Heap: Maximal heap support. Comparison: Comparisons on sequences. Numeric: Numeric-like algorithms. Memory: Memory operations. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 27/58

30 Invariant: Finding and searching Finding: adjacent_find: Finds two first elements that are equal or satisfy a predicate. find: Finds the first element with a value. find_if: Finds the first element satisfying a predicate. find_if_not: Finds the first element not satisfying a predicate. Searching search: Searches for a subsequence within a sequence. search_n: Searches n occurrences of a subsequence within a sequence. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 28/58

31 Finding in a sequence Examples vector<int> v = get_values_vector(); count_if(par, begin(v), end(v), []( int x) { return x>0; }) ; auto p = find (par, begin(v), end(v), 0); auto q = find_if (par, begin(v), end(v), []( int x) { return (x>0) && (x<10); } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 29/58

32 Invariant: Iterating Iterating for_each: Applies a function to all elements in a sequence. for_each_n: Applies a function to the first n elements in a sequence. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 30/58

33 Iterating Counting primes long count_primes(const std::vector<int> & v) { long count; std :: for_each(std::par, v.begin(), v.end(), [&]( int n) { if (is_prime(n)) count++; }) ; return count; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 31/58

34 Iterating Counting primes long count_primes(const std::vector<int> & v) { long count; std :: for_each(std::par, v.begin(), v.end(), [&]( int n) { if (is_prime(n)) count++; }) ; return count; } Can you spot the problem? cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 31/58

35 Iterating Counting primes long count_primes(const std::vector<int> & v) { long count; std :: for_each(std::par, v.begin(), v.end(), [&]( int n) { if (is_prime(n)) count++; }) ; return count; } Can you spot the problem? Hint: A data race condition. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 31/58

36 Iterating Counting primes long count_primes(const std::vector<int> & v) { std :: atomic<long> count; std :: for_each(std::par, v.begin(), v.end(), [&]( int n) { if (is_prime(n)) count++; }) ; return count.load() ; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 32/58

37 Iterating Counting primes long count_primes(const std::vector<int> & v) { std :: atomic<long> count; std :: for_each(std::par, v.begin(), v.end(), [&]( int n) { if (is_prime(n)) count++; }) ; return count.load() ; } Lesson 1: Avoid iterating and modifying. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 32/58

38 Iterating Counting primes long count_primes(const std::vector<int> & v) { std :: atomic<long> count; std :: for_each(std::par, v.begin(), v.end(), [&]( int n) { if (is_prime(n)) count++; }) ; return count.load() ; } Lesson 1: Avoid iterating and modifying. Lesson 2: If needed, add concurrency control. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 32/58

39 Invariant: Comparing, checking and counting Comparing equal: Compares two sequences element by element. mismatch: Determines the first position in which two sequences differ. Checking: all_of: Checks if a predicate is true for all elements. none_of: Checks if a predicate is false for all the elements. any_of: Checks if a predicate is true for any of the elements. Counting count: Counts the number of elements equal to a value. count_if: Counts the number of elements that satisfy a predicate. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 33/58

40 Counting Counting primes long count_primes(const std::vector<int> & v) { return std :: count_if(std :: par, v.begin(), v.end(), [&]( int n) { return is_prime(n); }) ; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 34/58

41 Counting Counting primes long count_primes(const std::vector<int> & v) { return std :: count_if(std :: par, v.begin(), v.end(), [&]( int n) { return is_prime(n); }) ; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 34/58

42 Modifying Copying/Moving copy: Copies a sequence of elements. copy_if: Copies elements from a sequences satisfying a predicate. copy_n: Copies the n first elements from a sequence. move: Moves a sequence of elements. swap_ranges: Swaps two sequences element by element. Replacement replace: Replaces all values from a sequence equal to a value with another one. replace_if: Replaces all values from a sequence satisfying a predicate with another value. replace_copy: Copies values from a sequence replacing elements equal to a value with another one. replace_copy_if: Copies values from a sequence replacing elements satisfying a predicate with another value. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 35/58

43 Modifying Filling fill: Fills a sequence with a value. fill_n: Fills the n first elements with a value. Value generation generate: Fills a sequence with the result of invoking a function. generate_n: Fills the n first elements with the result of invoking a function. Rearranging reverse: Inverts order of elements in a sequence. reverse_copy: Copies inverting orders of elements in a sequence. rotate: Rotates order of elements in a sequence. rotate_copy: Copies values from a sequence rotating order. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 36/58

44 Modifying Removal remove: Removes elements equal to a value. remove_if: Removes elements satisfying a predicate. remove_copy: Copies elements from a sequence except those equal to a value. remove_copy_if: Copies elements from a sequence except those satisfying a predicate. unique: Removes consecutive duplicates in a sequence. unique_copy: Copies elements from a sequence without repeating duplicates. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 37/58

45 Modifying Mapping pattern transform: Applies a function to one or two sequences to generate another sequence. using myvector = std::double<vector>; myvector addvec(const myvector & v, const myvector & w) { myvector r(v.size () ) ; std :: transform(par, v.begin(), v.end(), w.begin(), r.begin(), []( double x, double y) { return x+y; } }) ; return r ; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 38/58

46 Partitioning operations is_partitioned: Determines if a sequence is partitioned with respect a predicate. partition: Divides a sequence in two using a predicate as criteria. partition_copy: Copies a sequence divided in two using a predicate as criteria. stable_partition: Divides a sequence in two using a predicate as criteria and preserving relative order. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 39/58

47 Sorting operations is_sorted: Determines if a sequence is sorted. is_sorted_until: Determines the longest sorted subsequence. nth_element: Partially sorts ensuring position of an element as pivot. partial_sort: Sorts the first n elements in a sequence. partial_sort_copy: Copies and partially sorts the first n elements from a sequence. sort: Sorts a sequence in ascending order. stable_sort: Sorts a sequence preserving order among equal elements. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 40/58

48 Set operations includes: Determines if a sequence is a subset from another. inplace_merge: Merges two consecutive subsequences that are already sorted. merge: Merges two sequences already sorted. set_difference: Computes the set difference between two sequences. set_intersection: Computes set intersection between tow sequences. set_symmetric_difference: Computes set symmetric difference between two sequences. set_union: Computes set union between two sequences. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 41/58

49 Heap operations is_heap: Determines if a sequences is a maximal heap. is_heap_until: Finds the longest subsequence that is a maximal heap. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 42/58

50 Minimum and maximum operations lexicographical_compare: Determines if a sequence is lexicographically less than another one. max_element: Determines the greater element in a sequence. min_element: Determines the lowest element in a sequence. minmax_element: Determines the greater and the lowest element in a sequence. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 43/58

51 Memory operations uninitialized_copy: Copies a sequence into an uninitialized memory area. uninitialized_copy_n: Copies a sequence of n values into an uninitialized memory area. uninitialized_fill: Copies a value repeatedly into an uninitialized memory area. uninitialized_fill_n: Copies a value repeatedly (n times) into an uninitialized memory area. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 44/58

52 Numeric-like operations Reductions reduce: Performs a reduction operation on a sequence. Map/Reduce transform_reduce: Performs a reduction operation on the transformation of a sequence. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 45/58

53 Reducing sequences Adding elements double addvalues(const std::vector<double> & v) { return std :: reduce(std::par, v.begin(), v.end(), 0.0, []( double x, double y) { return x+y; } ) ; } Notes: The operation cannot invalidate iterators. The operation cannot modify values in the sequence. Might be non-deterministic is the operation is: Non-associative. Non-commutative. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 46/58

54 Other versions of reduce If no operation is provided, std::plus<>() is used. If no initial value is provided, a default constructed value from iterator s value type is used. Adding elements double addvalues(const std::vector<double> & v) { return std :: reduce(std::par, v.begin(), v.end()); } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 47/58

55 Map-reduce Named in C++ transform_reduce to avoid conflicts. Takes two operations: An unary operation to transform each element. A binary operation to reduce results of transformations. Sum of squares double sum_squares(const std::vector<double> & v) { return std :: transform_reduce(std::par, v.begin(), v.end(), 0.0, []( double x) { return std :: pow(x,2); }, []( double x, double y) { return x+y; } ) ; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 48/58

56 Binary map/reduce Takes to input sequences. The transform stage pairs elements from both sequences. Scalar product double scalar_product(const std::vector<double> & v) { return std :: transform_reduce(std::par, v.begin(), v.end(), w.begin(), 0.0, []( double x, double y) { return x y; }, []( double x, double y) { return x+y; } ) ; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 49/58

57 Cannonical map/reduce example Word count using text = std :: vector<std:: string >; cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 50/58

58 Cannonical map/reduce example Word count using text = std :: vector<std:: string >; using freq_table = std :: map<std::string, long>; cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 50/58

59 Cannonical map/reduce example Word count using text = std :: vector<std:: string >; using freq_table = std :: map<std::string, long>; freq_table count_words(const text & words) { return std :: transform_reduce(std::par, words.begin(), words.end(), cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 50/58

60 Cannonical map/reduce example Word count using text = std :: vector<std:: string >; using freq_table = std :: map<std::string, long>; freq_table count_words(const text & words) { return std :: transform_reduce(std::par, words.begin(), words.end(), freq_table {}, cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 50/58

61 Cannonical map/reduce example Word count using text = std :: vector<std:: string >; using freq_table = std :: map<std::string, long>; freq_table count_words(const text & words) { return std :: transform_reduce(std::par, words.begin(), words.end(), freq_table {}, []( std :: string word) > freq_table { return{word,1}; }, cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 50/58

62 Cannonical map/reduce example Word count using text = std :: vector<std:: string >; using freq_table = std :: map<std::string, long>; freq_table count_words(const text & words) { return std :: transform_reduce(std::par, words.begin(), words.end(), freq_table {}, []( std :: string word) > freq_table { return{word,1}; }, []( freq_table & lhs, const freq_table & rhs) { cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 50/58

63 Cannonical map/reduce example Word count using text = std :: vector<std:: string >; using freq_table = std :: map<std::string, long>; freq_table count_words(const text & words) { return std :: transform_reduce(std::par, words.begin(), words.end(), freq_table {}, []( std :: string word) > freq_table { return{word,1}; }, []( freq_table & lhs, const freq_table & rhs) { for (auto & [w,n] : rhs) { lhs[w] += n; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 50/58

64 Cannonical map/reduce example Word count using text = std :: vector<std:: string >; using freq_table = std :: map<std::string, long>; freq_table count_words(const text & words) { return std :: transform_reduce(std::par, words.begin(), words.end(), freq_table {}, []( std :: string word) > freq_table { return{word,1}; }, []( freq_table & lhs, const freq_table & rhs) { for (auto & [w,n] : rhs) { lhs[w] += n; } return lhs; } ) ; } cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 50/58

65 Numeric-like operations Scan operations Generate a sequence of cummulative reductions Scan exclusive_scan: Performs an exclusive scan operation on a sequence. inclusive_scan: Performs an inclusive scan operation on a sequence. transform_exclusive_scan: Performs an exclusive scan operation on the transformation of a sequence. transform_inclusive_scan: Performs an inclusive scan operation on the transformation of a sequence. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 51/58

66 Using scans to compute CDF CDF computation vector<int> histogram = compute\_histogram(); vector<int> cdf(histogram.size()) ; std :: inclusive_scan(std :: par, histogram.begin(), histogram.end(), cdf.begin(), 0, []( int x, int y) { return x+y; } ) ; cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 52/58

67 Using scans to compute CDF CDF computation vector<int> histogram = compute\_histogram(); vector<int> cdf(histogram.size()) ; std :: inclusive_scan(std :: par, histogram.begin(), histogram.end(), cdf.begin(), 0, []( int x, int y) { return x+y; } ) ; What if I want to saturate the histogram? Negative values become 0. Values over 255 become 255. cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 52/58

68 Using scans to compute CDF Saturated CDF computation vector<int> histogram = compute\_histogram(); vector<int> cdf(histogram.size()) ; std :: inclusive_scan(std :: par, histogram.begin(), histogram.end(), cdf.begin(), 0, []( int x) { if (x<0) return 0; if (x>255) return 255; return x; }, []( int x, int y) { return x+y; } ) ; cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 53/58

69 More? 1 Introduction to generic programming 2 STL: Standard Template Library 3 Execution policies 4 5 More? cbea J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es) 54/58

70 More? using std::cpp 2019 cbea J. Daniel Garcia 55/58

71 More? CFP abierto cbea J. Daniel Garcia 56/58

72 More? Curso de C++ (25,26,27 marzo) cbea J. Daniel Garcia 57/58

73 More? J. Daniel Garcia Universidad Carlos III de Madrid November 23, 2018 cbea J. Daniel Garcia 58/58

Working Draft, Technical Specification for C++ Extensions for Parallelism, Revision 1

Working Draft, Technical Specification for C++ Extensions for Parallelism, Revision 1 Document Number: N3960 Date: 2014-02-28 Reply to: Jared Hoberock NVIDIA Corporation jhoberock@nvidia.com Working Draft, Technical Specification for C++ Extensions for Parallelism, Revision 1 Note: this

More information

Programming Languages Technical Specification for C++ Extensions for Parallelism

Programming Languages Technical Specification for C++ Extensions for Parallelism ISO 05 All rights reserved ISO/IEC JTC SC WG N4409 Date: 05-04-0 ISO/IEC DTS 9570 ISO/IEC JTC SC Secretariat: ANSI Programming Languages Technical Specification for C++ Extensions for Parallelism Warning

More information

Parallelism and Concurrency in C++17 and C++20. Rainer Grimm Training, Coaching and, Technology Consulting

Parallelism and Concurrency in C++17 and C++20. Rainer Grimm Training, Coaching and, Technology Consulting Parallelism and Concurrency in C++17 and C++20 Rainer Grimm Training, Coaching and, Technology Consulting www.grimm-jaud.de Multithreading and Parallelism in C++ Multithreading in C++17 Parallel STL The

More information

Boost.Compute. A C++ library for GPU computing. Kyle Lutz

Boost.Compute. A C++ library for GPU computing. Kyle Lutz Boost.Compute A C++ library for GPU computing Kyle Lutz GPUs (NVIDIA, AMD, Intel) Multi-core CPUs (Intel, AMD) STL for Parallel Devices Accelerators (Xeon Phi, Adapteva Epiphany) FPGAs (Altera, Xilinx)

More information

Major Language Changes, pt. 1

Major 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 information

Concurrency and Parallelism with C++17 and C++20. Rainer Grimm Training, Coaching and, Technology Consulting

Concurrency and Parallelism with C++17 and C++20. Rainer Grimm Training, Coaching and, Technology Consulting Concurrency and Parallelism with C++17 and C++20 Rainer Grimm Training, Coaching and, Technology Consulting www.modernescpp.de Concurrency and Parallelism in C++ Concurrency and Parallelism in C++17 Parallel

More information

To use various types of iterators with the STL algorithms ( ). To use Boolean functions to specify criteria for STL algorithms ( 23.8).

To use various types of iterators with the STL algorithms ( ). To use Boolean functions to specify criteria for STL algorithms ( 23.8). CHAPTER 23 STL Algorithms Objectives To use various types of iterators with the STL algorithms ( 23.1 23.20). To discover the four types of STL algorithms: nonmodifying algorithms, modifying algorithms,

More information

Lecture 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. 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 information

Scientific programming (in C++)

Scientific programming (in C++) Scientific programming (in C++) F. Giacomini INFN-CNAF School on Open Science Cloud Perugia, June 2017 https://baltig.infn.it/giaco/201706_perugia_cpp What is C++ C++ is a programming language that is:

More information

C++ Standard Template Library

C++ Standard Template Library C++ Standard Template Library CS 247: Software Engineering Principles Generic Algorithms A collection of useful, typesafe, generic (i.e., type-parameterized) containers that - know (almost) nothing about

More information

Functors. Cristian Cibils

Functors. 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 information

Parallel Programming with OpenMP and Modern C++ Alternatives

Parallel Programming with OpenMP and Modern C++ Alternatives Parallel Programming with OpenMP and Modern C++ Alternatives Michael F. Hava and Bernhard M. Gruber RISC Software GmbH Softwarepark 35, 4232 Hagenberg, Austria RISC Software GmbH Johannes Kepler University

More information

When we program, we have to deal with errors. Our most basic aim is correctness, but we must

When 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 information

C++ - parallelization and synchronization. Jakub Yaghob Martin Kruliš

C++ - parallelization and synchronization. Jakub Yaghob Martin Kruliš C++ - parallelization and synchronization Jakub Yaghob Martin Kruliš The problem Race conditions Separate threads with shared state Result of computation depends on OS scheduling Race conditions simple

More information

C++ - parallelization and synchronization. David Bednárek Jakub Yaghob Filip Zavoral

C++ - parallelization and synchronization. David Bednárek Jakub Yaghob Filip Zavoral C++ - parallelization and synchronization David Bednárek Jakub Yaghob Filip Zavoral The problem Race conditions Separate threads with shared state Result of computation depends on OS scheduling Race conditions

More information

More STL algorithms (revision 2)

More STL algorithms (revision 2) Doc No: N2666=08-0176 Reply to: Matt Austern Date: 2008-06-11 More STL algorithms (revision 2) This paper proposes a number of nonstandard STL-style algorithms for inclusion in the

More information

MODULE 37 --THE STL-- ALGORITHM PART V

MODULE 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 information

I/O and STL Algorithms

I/O and STL Algorithms CS193D Handout 21 Winter 2005/2006 February 29, 2006 I/O and STL Algorithms See also: Chapter 14, Chapter 22 I/O and STL Algorithms CS193D, 2/29/06 1 Raw Input and Output ostream::put(char ch); ostream::write(const

More information

Exceptions, Templates, and the STL

Exceptions, Templates, and the STL Exceptions, Templates, and the STL CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 16 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/

More information

Working Draft, Technical Specification for C++ Extensions for Parallelism

Working Draft, Technical Specification for C++ Extensions for Parallelism Document Number: N3850 Date: 2014-01-17 Reply to: Jared Hoberock NVIDIA Corporation jhoberock@nvidia.com Working Draft, Technical Specification for C++ Extensions for Parallelism Note: this is an early

More information

Efficient C++ Programming and Memory Management

Efficient C++ Programming and Memory Management Efficient C++ Programming and Memory Management F. Giacomini INFN-CNAF ESC 17 Bertinoro, 22-28 October 2017 https://baltig.infn.it/giaco/cpp-memory-esc17 Outline Introduction Type deduction Function, function

More information

use static size for this buffer

use 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 information

More STL algorithms. Design Decisions. Doc No: N2569= Reply to: Matt Austern Date:

More STL algorithms. Design Decisions. Doc No: N2569= Reply to: Matt Austern Date: Doc No: N2569=08-0079 Reply to: Matt Austern Date: 2008-02-29 More STL algorithms This paper proposes a number of nonstandard STL-style algorithms for inclusion in the standard. Nothing

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 22, 2017 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates

More information

STL: C++ Standard Library

STL: 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 information

MODULE 35 --THE STL-- ALGORITHM PART III

MODULE 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 information

Chapter 5. The Standard Template Library.

Chapter 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 information

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

STL 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 information

COMP6771 Advanced C++ Programming

COMP6771 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 information

Generic Programming with JGL 4

Generic Programming with JGL 4 Generic Programming with JGL 4 By John Lammers Recursion Software, Inc. July 2004 TABLE OF CONTENTS Abstract...1 Introduction to Generic Programming...1 How does Java support generic programming?...2 The

More information

New Iterator Concepts

New 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 information

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

Type 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 information

COEN244: Class & function templates

COEN244: 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 information

Templates and Vectors

Templates 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 information

The Cut and Thrust of CUDA

The Cut and Thrust of CUDA The Cut and Thrust of CUDA Luke Hodkinson Center for Astrophysics and Supercomputing Swinburne University of Technology Melbourne, Hawthorn 32000, Australia May 16, 2013 Luke Hodkinson The Cut and Thrust

More information

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy CAAM 420 Fall 2012 Lecture 29 Duncan Eddy November 7, 2012 Table of Contents 1 Templating in C++ 3 1.1 Motivation.............................................. 3 1.2 Templating Functions........................................

More information

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type. CS 7A - Fall 2016 - Midterm 1 10/20/16 Write responses to questions 1 and 2 on this paper or attach additional sheets, as necessary For all subsequent problems, use separate paper Do not use a computer

More information

SFU CMPT Topic: Function Objects

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 information

The Standard Template Library. EECS 211 Winter 2018

The Standard Template Library. EECS 211 Winter 2018 The Standard Template Library EECS 211 Winter 2018 2 Problem: finding the maximum element of a vector A simple fixed-size vector struct: struct Int_vec int* data; size_t size; ; 3 Solution: max_int_vec

More information

CS11 Advanced C++ Fall Lecture 1

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 information

Item 3: Predicates, Part 2: Matters of State

Item 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 information

Distributed Real-Time Control Systems. Lecture 16 C++ Libraries Templates

Distributed Real-Time Control Systems. Lecture 16 C++ Libraries Templates Distributed Real-Time Control Systems Lecture 16 C++ Libraries Templates 1 C++ Libraries One of the greatest advantages of C++ is to facilitate code reuse. If code is well organized and documented into

More information

Foundations of Programming, Volume I, Linear structures

Foundations of Programming, Volume I, Linear structures Plan 1. Machine model. Objects. Values. Assignment, swap, move. 2. Introductory algorithms: advance, distance, find, copy. Iterators: operations, properties, classification. Ranges and their validity.

More information

Contents. 2 Introduction to C++ Programming,

Contents. 2 Introduction to C++ Programming, cppfp2_toc.fm Page vii Thursday, February 14, 2013 9:33 AM Chapter 24 and Appendices F K are PDF documents posted online at www.informit.com/title/9780133439854 Preface xix 1 Introduction 1 1.1 Introduction

More information

CS11 Advanced C++ Spring 2018 Lecture 2

CS11 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 information

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

THE 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 information

Working with Batches of Data

Working 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 information

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11

Container 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 information

Contracts programming for C++20

Contracts programming for C++20 Contracts programming for C++20 Current proposal status J. Daniel Garcia ARCOS Group University Carlos III of Madrid Spain February 27, 2018 cbed J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es)

More information

Data_Structures - Hackveda

Data_Structures - Hackveda Data_Structures - Hackveda ( Talk to Live Mentor) Become a Data Structure and Algorithm Professional - (Beginner - Advanced) Skill level: Beginner - Advanced Training fee: INR 15999 only (Topics covered:

More information

Outline. Function calls and results Returning objects by value. return value optimization (RVO) Call by reference or by value?

Outline. Function calls and results Returning objects by value. return value optimization (RVO) Call by reference or by value? Outline EDAF50 C++ Programming 6... 1 Function calls 2 Sven Gestegård Robertz Computer Science, LTH 2018 3 Standard library algorithms Insert iterators 4 Iterators Different kinds of iterators stream iterators

More information

G Programming Languages Spring 2010 Lecture 11. Robert Soulé, New York University

G 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 information

Lambda functions. Zoltán Porkoláb: C++11/14 1

Lambda 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 information

Bigger Better More. The new C++ Standard Library. Thomas Witt April Copyright 2009 Thomas Witt

Bigger Better More. The new C++ Standard Library. Thomas Witt April Copyright 2009 Thomas Witt Bigger Better More The new C++ Standard Library Thomas Witt April 24 2009 Landscape C99 (2003) Technical Report on C++ Library Extensions (TR1) Jan 2006 Committee Draft (CD) Oct 2008 C++ 0x TR2.NET, Java,

More information

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Standard Template Library

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Standard Template Library CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Standard Template Library 1 Standard Template Library Need to understand basic data types, so we build them ourselves Once understood, we

More information

Introduction to GIL, Boost and Generic Programming

Introduction to GIL, Boost and Generic Programming Introduction to GIL, Boost and Generic Programming Hailin Jin Advanced Technology Labs Adobe Systems Incorporated http://www.adobe.com/technology/people/sanjose/jin.html 1 Outline GIL Boost Generic programming

More information

Using Library Algorithms. Lectures 12 and 13 Hartmut Kaiser hkaiser/fall_2013/csc1254.

Using Library Algorithms. Lectures 12 and 13 Hartmut Kaiser  hkaiser/fall_2013/csc1254. Using Library Algorithms Lectures 12 and 13 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2013/csc1254.html Programming Principle of the Day Avoid Creating a YAGNI (You aren t

More information

C++ 11 and the Standard Library: Containers, Iterators, Algorithms

C++ 11 and the Standard Library: Containers, Iterators, Algorithms and the Standard Library:,, Comp Sci 1575 Outline 1 2 3 4 Outline 1 2 3 4 #i n clude i n t main ( ) { i n t v a l u e 0 = 5 ; // C++ 98 i n t v a l u e 1 ( 5 ) ; // C++ 98 i n t v a

More information

Module 9. Templates & STL

Module 9. Templates & STL Module 9 Templates & STL Objectives In this module Learn about templates Construct function templates and class templates STL 2 Introduction Templates: enable you to write generic code for related functions

More information

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be Operator Overloading and Templates Week 6 Gaddis: 8.1, 14.5, 16.2-16.4 CS 5301 Spring 2015 Jill Seaman Linear Search! Search: find a given target item in an array, return the index of the item, or -1 if

More information

C++ Modern and Lucid C++ for Professional Programmers

C++ Modern and Lucid C++ for Professional Programmers Informatik C++ Modern and Lucid C++ for Professional Programmers part 9 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2015 Functors and Parameterizing STL Functors, Lambdas,

More information

Exercise 6.2 A generic container class

Exercise 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 information

Deitel Series Page How To Program Series

Deitel Series Page How To Program Series Deitel Series Page How To Program Series Android How to Program C How to Program, 7/E C++ How to Program, 9/E C++ How to Program, Late Objects Version, 7/E Java How to Program, 9/E Java How to Program,

More information

C++ How To Program 10 th Edition. Table of Contents

C++ How To Program 10 th Edition. Table of Contents C++ How To Program 10 th Edition Table of Contents Preface xxiii Before You Begin xxxix 1 Introduction to Computers and C++ 1 1.1 Introduction 1.2 Computers and the Internet in Industry and Research 1.3

More information

GrPPI. GrPPI. Generic Reusable Parallel Patterns Interface. ARCOS Group University Carlos III of Madrid Spain. January 2018

GrPPI. GrPPI. Generic Reusable Parallel Patterns Interface. ARCOS Group University Carlos III of Madrid Spain. January 2018 GrPPI Generic Reusable Parallel Patterns Interface ARCOS Group University Carlos III of Madrid Spain January 2018 cbed 1/105 Warning c This work is under Attribution-NonCommercial- NoDerivatives 4.0 International

More information

CSC 427: Data Structures and Algorithm Analysis. Fall 2004

CSC 427: Data Structures and Algorithm Analysis. Fall 2004 CSC 47: Data Structures and Algorithm Analysis Fall 4 Associative containers STL data structures and algorithms sets: insert, find, erase, empty, size, begin/end maps: operator[], find, erase, empty, size,

More information

Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)

Chapter 16: Exceptions, Templates, and the Standard Template Library (STL) Chapter 16: Exceptions, Templates, and the Standard Template Library (STL) 6.1 Exceptions Exceptions Indicate that something unexpected has occurred or been detected Allow program to deal with the problem

More information

Unit 4 Basic Collections

Unit 4 Basic Collections Unit 4 Basic Collections General Concepts Templates Exceptions Iterators Collection (or Container) Classes Vectors (or Arrays) Sets Lists Maps or Tables C++ Standard Template Library (STL Overview A program

More information

CSCI 104 Templates. Mark Redekopp David Kempe

CSCI 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 information

CPSC 427a: Object-Oriented Programming

CPSC 427a: Object-Oriented Programming CPSC 427a: Object-Oriented Programming Michael J. Fischer Lecture 17 November 1, 2011 CPSC 427a, Lecture 17 1/21 CPSC 427a, Lecture 17 2/21 CPSC 427a, Lecture 17 3/21 A bit of history C++ standardization.

More information

Chapter 19 Vector, templates, and exceptions

Chapter 19 Vector, templates, and exceptions Chapter 19 Vector, templates, and exceptions Dr. Hyunyoung Lee Based on slides by Dr. Bjarne Stroustrup www.stroustrup.com/programming Abstract This is the third of the lectures exploring the design of

More information

The Set of Natural Code. Mark Isaacson

The Set of Natural Code. Mark Isaacson The Set of Natural Code Mark Isaacson An invitation for questions A Little History, C to C++ void* myccontainer = containermake(); containeraddelt(myccontainer, 5); containerfree(myccontainer); vector

More information

Other C++11/14 features

Other C++11/14 features Other C++11/14 features Auto, decltype Range for Constexpr Enum class Initializer list Default and delete functions Etc. Zoltán Porkoláb: C++11/14 1 Auto, decltype template void printall(const

More information

CS 247: Software Engineering Principles. C++ lambdas, bind, mem_fn. U Waterloo CS247 (Spring 2017)

CS 247: Software Engineering Principles. C++ lambdas, bind, mem_fn. U Waterloo CS247 (Spring 2017) CS 247: Software Engineering Principles C++ lambdas, bind, mem_fn 1 Recap: Can Specialize STL Algorithms void quote( string word ) { } cout

More information

How the Adapters and Binders Work

How the Adapters and Binders Work What code gets generated when we write #include #include #include using namespace std;... vector v; void foo(char, int); How the Adapters and Binders Work David Kieras

More information

CSCI 104 Templates. Mark Redekopp David Kempe

CSCI 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 information

Programming in C++ using STL. Rex Jaeschke

Programming 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 information

TDDD38 - Advanced programming in C++

TDDD38 - 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 information

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt Operator Overloading and Templates Week 6 Gaddis: 8.1, 14.5, 16.2-16.4 CS 5301 Fall 2015 Jill Seaman Linear Search! Search: find a given target item in an array, return the index of the item, or -1 if

More information

Functions. Ali Malik

Functions. 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 information

The Ada Standard Generic Library (SGL)

The 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 information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 16: STL, C++1y (ramviyas@kth.se) Overview Overview Lecture 16: STL and C++1y Reminders Wrap up C++11 Reminders The help sessions and deadline C++ help session: Fri 24.10.2015, 15:00-17:00, Room

More information

Contracts programming for C++20

Contracts programming for C++20 Contracts programming for C++20 Current proposal status J. Daniel Garcia ARCOS Group University Carlos III of Madrid Spain April, 28th, 2017 cbed J. Daniel Garcia ARCOS@UC3M (josedaniel.garcia@uc3m.es)

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2305/lab33.C Input: under control of main function Output: under control of main function Value: 3 The Shell sort, named after its inventor Donald Shell, provides a simple and efficient

More information

CS 211 Winter 2004 Sample Final Exam (Solutions)

CS 211 Winter 2004 Sample Final Exam (Solutions) CS 211 Winter 2004 Sample Final Exam (Solutions) Instructor: Brian Dennis, Assistant Professor TAs: Tom Lechner, Rachel Goldsborough, Bin Lin March 16, 2004 Your Name: There are 6 problems on this exam.

More information

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2

Today. 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 information

C and C++ Courses. C Language

C and C++ Courses. C Language C Language The "C" Language is currently one of the most widely used programming languages. Designed as a tool for creating operating systems (with its help the first Unix systems were constructed) it

More information

CUDA Toolkit 4.2 Thrust Quick Start Guide. PG _v01 March 2012

CUDA Toolkit 4.2 Thrust Quick Start Guide. PG _v01 March 2012 CUDA Toolkit 4.2 Thrust Quick Start Guide PG-05688-040_v01 March 2012 Document Change History Version Date Authors Description of Change 01 2011/1/13 NOJW Initial import from wiki. CUDA Toolkit 4.2 Thrust

More information

Parallel STL in today s SYCL Ruymán Reyes

Parallel STL in today s SYCL Ruymán Reyes Parallel STL in today s SYCL Ruymán Reyes ruyman@codeplay.com Codeplay Research 15 th November, 2016 Outline 1 Parallelism TS 2 The SYCL parallel STL 3 Heterogeneous Execution with Parallel STL 4 Conclusions

More information

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Agenda. 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 information

CS11 Introduction to C++ Spring Lecture 8

CS11 Introduction to C++ Spring Lecture 8 CS11 Introduction to C++ Spring 2013-2014 Lecture 8 Local Variables string getusername() { string user; } cout user; return user;! What happens to user when function

More information

General Advise: Don t reinvent the wheel

General Advise: Don t reinvent the wheel General Advise: Don t reinvent the wheel Use libraries: Discover the available open source libraries for your application Examples: STL, boost, thrust libraries Info on C++ and STL: http://www.cplusplus.com/reference,

More information

Introduction to C++11 and its use inside Qt

Introduction to C++11 and its use inside Qt Introduction to C++11 and its use inside Qt Olivier Goffart February 2013 1/43 Introduction to C++11 and its use inside Qt About Me http://woboq.com http://code.woboq.org 2/43 Introduction to C++11 and

More information

GridKa School 2013: Effective Analysis C++ Templates

GridKa School 2013: Effective Analysis C++ Templates GridKa School 2013: Effective Analysis C++ Templates Introduction Jörg Meyer, Steinbuch Centre for Computing, Scientific Data Management KIT University of the State of Baden-Wuerttemberg and National Research

More information

A Parallel Algorithms Library N3724

A 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 information

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Appendix. 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 information

MODULE 33 --THE STL-- ALGORITHM PART I

MODULE 33 --THE STL-- ALGORITHM PART I MODULE 33 --THE STL-- ALGORITHM PART I My Training Period: hours Note: Compiled using Microsoft Visual C++.Net, win32 empty console mode application. g++ compilation examples given at the end of this Module.

More information

Recap: Can Specialize STL Algorithms. Recap: Can Specialize STL Algorithms. C++11 Facilities to Simplify Supporting Code

Recap: Can Specialize STL Algorithms. Recap: Can Specialize STL Algorithms. C++11 Facilities to Simplify Supporting Code Recap: Can Specialize STL Algorithms CS 247: Software Engineering Principles C++ lambdas, bind, mem_fn void quote( string word ) { cout

More information

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it Reference LearnCPP.com has many excellent C++ tutorials The auto keyword In C++11, the meaning of the auto keyword has changed, and it is now a useful declaration feature. Consider: double d = 5.0; If

More information

Topics. Modularity and Object-Oriented Programming. Dijkstra s Example (1969) Stepwise Refinement. Modular program development

Topics. Modularity and Object-Oriented Programming. Dijkstra s Example (1969) Stepwise Refinement. Modular program development Topics Modularity and Object-Oriented Programming 申 @ 케이유티 Modular program development Step-wise refinement Interface, specification, and implementation Language support for modularity Procedural abstraction

More information