SlideShare ist ein Scribd-Unternehmen logo
1 von 77
Downloaden Sie, um offline zu lesen
Introduction to C++ STL
CodeClass[5]
Disclaimer: Slides taken from various sources and modified as required
C++ Generic Programming: Templates
#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
Output:
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
2
STL – Standard Template Library
 Collections of useful classes for common data
structures
 Ability to store objects of any type (template)
 Study of containers
 Containers form the basis for treatment of data
structures
 Container – class that stores a collection of data
 STL consists of 10 container classes:
 Sequence containers
 Adapter containers
 Associative containers
3
Why use STL?
 STL offers an assortment of containers
 STL publicizes the time and storage complexity of its
containers
 STL containers grow and shrink in size automatically
 STL provides built-in algorithms for processing containers
 STL provides iterators that make the containers and
algorithms flexible and efficient.
 STL is extensible which means that users can add new
containers and new algorithms such that:
 STL algorithms can process STL containers as well as user defined
containers
 User defined algorithms can process STL containers as well user
defined containers
4
Standard Template Library
 The standard template library (STL) contains
 Containers
 Algorithms
 Iterators
 A container is a way that stored data is organized in
memory, for example an array of elements.
 Algorithms in the STL are procedures that are applied to
containers to process their data, for example search for an
element in an array, or sort an array.
 Iterators are a generalization of the concept of pointers,
they point to elements in a container, for example you can
increment an iterator to point to the next element in an
array
5
Strings
 In C we used char * to represent a string.
 The C++ standard library provides a common
implementation of a string class abstraction
named string.
6
Hello World - C
#include <stdio.h>
void main()
{
// create string ‘str’ = “Hello world!”
char *str = “Hello World!”;
//OR
char str1[] = “Hello World!”;
printf(“%sn”, str);
}
7
Hello World – C++
#include <iostream> //for cout
#include <cstdio> //for printf
#include <string>
using namespace std;
int main()
{
// create string ‘str’ = “Hello world!”
string str = “Hello World!”;
char str1[] = “Hello World!”;
cout << str << endl;
printf(“%s”,str1);
return 0;
}
8
String
 To use the string type simply include its
header file.
#include <string>
9
Creating strings
string str = “some text”;
or
string str(“some text”);
other ways:
string s1(7,‘a’);
string s2 = s1;
10
string length
The length of string is returned by its
size() operation.
#include <string>
string str = “something”;
cout << “The size of “
<< str
<< “is “ << str.size()
<< “characters.” << endl;
11
The size method
str.size() ???
In C we had structs containing only data, In
C++, we have :
class string
{
…
public:
…
unsigned int size();
…
};
12
String concatenation
concatenating one string to another is done
by the ‘+’ operator.
string str1 = “Here ”;
string str2 = “comes the sun”;
string concat_str = str1 + str2;
13
String comparison
To check if two strings are equal use
the ‘==‘ operator.
string str1 = “Here ”;
string str2 = “comes the sun”;
if ( str1 == str2 )
/* do something */
else
/* do something else */
14
String assignment
To assign one string to another
use the “=“ operator.
string str1 = “Sgt. Pappers”;
string str2 = “lonely hearts club bend”;
str2 = str1;
Now : str2 equals “Sgt. Pappers”
15
Containers, Iterators, Algorithms
Container
Algorithm
Iterator
Container
Iterator
Algorithm
Objects
Iterator
Iterator
Algorithm
Algorithms use iterators to interact with objects
stored in containers
16
Containers
 A container is a way to store data, either built-in data
types like int and float, or class objects
 The STL provides several basic kinds of containers
 <vector> : one-dimensional array (similar to C array, but dynamic)
 <list> : double linked list
 <deque> : double-ended queue
 <queue> : queue
 <stack> : stack
 <set> : set of ordered keys
 <map> : associative array (set of ordered key/value pairs)
17
Sequence Containers
 A sequence container stores a set of elements in sequence, in
other words each element (except for the first and last one) is
preceded by one specific element and followed by another,
<vector>, <list> and <deque> are sequential containers
 In an ordinary C++ array the size is fixed and can not change
during run-time, it is also tedious to insert or delete elements.
Advantage: quick random access
 <vector> is an expandable array that can shrink or grow in size,
but still has the disadvantage of inserting or deleting elements
in the middle
Vector should be your default choice, but choose wisely
Backward compatible with C : &v[0] points to the first element
18
Sequence Containers
 <list> is a ’traditional’ double linked list (each element
has points to its successor and predecessor), it is
quick to insert or delete elements but has v.slow
random access
 <deque> is a double-ended queue, that means one
can insert and delete elements from both ends, it is a
kind of combination between a stack (last in first out)
and a queue (first in first out) and constitutes a
compromise between a <vector> and a <list>
Offers random access, back and front insertion but
slower than vectors, no C compatibilty
19
Associative Containers
 An associative container is non-sequential but uses
a key to access elements. The keys, typically a
number or a string, are used by the container to
arrange the stored elements in a specific order,
for example in a dictionary the entries are ordered
alphabetically.
Offers O(log n) insertion and access
20
Associative Containers
 A <set> stores a number of items which contain keys. The
keys are the attributes used to order the items, for
example a set might store objects of the class. People
which are ordered alphabetically using their name
 A <map> stores pairs of objects: a key object and an
associated value object. A <map> is somehow similar to an
array except instead of accessing its elements with index
numbers, you access them with indices of an arbitrary
type.
 <set> and <map> only allow one key of each value,
whereas <multiset> and <multimap> allow multiple
identical key values 21
Defining a new vector
 Header file: <vector>
 Syntax: vector<of what>
 For example :
vector<int> - vector of integers.
vector<string> - vector of strings.
vector<int * > - vector of pointers to integers.
vector<Shape> - vector of Shape objects. Shape is a
user defined class.
 Two ways to use vector type: Array style, and STL style
22
Operations on vector
 iterator begin();
 iterator end();
 bool empty();
 void push_back(const T& x);
 iterator erase(iterator it);
 iterator erase(iterator first, iterator last);
 void clear();
 ….
23
Vector Container
12 7 9 21 13
int array[5] = {12, 7, 9, 21, 13 };
vector<int> v(array,array+5);
v.begin();
12 7 9 21
v.push_back(15);
12 7 9 21 15
12 7 9 21 15
v[3]
0 1 2 3 4
v.pop_back();
24
Vector Container
vector<int> v(3); // create a vector of ints of size 3
v[0]=23;
v[1]=12;
v[2]=9; // vector full
v.push_back(17); // put a new value at the end of array
for (int i=0; i<v.size(); i++) //member function size() of vector
printf(”%d ”,v[i]); // random access to i-th element
25
Vector Container
#include <vector>
#include <cstdio>
int arr[] = { 12, 3, 17, 8 }; // standard C array
vector<int> v(arr, arr+4); // initialize vector with C array
while ( ! v.empty()) // until vector is empty
{
printf(”%d ”, v.back() ); // output last element of vector
v.pop_back(); // delete the last element
}
26
Tip : vector<bool>
 Meyers: "As an STL container, there are really only two
things wrong with vector<bool>. First it's not an STL
containers. Second it doesn't hold bools. Other than
that, there's not much to object to." (Effective STL, p79)
 vector<bool> does not conform to STL requirements
 it stores bools in a packed representation (e.g. bitfield)
 Accessing it returns proxy objects to bools, not true
bools
 Use a deque<bool> or a bitset to store bools
 You won't get C compatibility (but C doesn't have bools
anyways)
27
Tip : reserve()
 Inserting elements may cause a memory
reallocation
 container is doubled in capacity
 elements are copied over
 Both string and vector let you increase capacity in
advance through reserve()
 May eliminate unnecessary reallocations
 Keeps safety of dynamic data structures over C arrays
 v.reserve(n)allocates memory for n objects
 Distinguish capacity (memory) and size (objects)
 Writing beyond the size of the container is still bad
28
Tip : size() and empty()
 You may check whether a container is empty by
writing c.size() == 0 or c.empty()
 However, with lists, which have a splice() function,
if splice() is O(1), size() must be O(n) and
conversely.
 Therefore, while empty() will always run in O(1),
size() may not. You should thus prefer calling
empty() to checking size() against zero.
29
vector<int>
array_
Iterators
 Iterators are pointer-like entities that are used to access
individual elements in a container.
 Often they are used to move sequentially from element to
element, a process called iterating through a container.
17
4
23
12
size_ 4
vector<int>::iterator
The iterator corresponding to
the class vector<int> is of
the type vector<int>::iterator
30
Iterators
 The member functions begin() and end() return an
iterator to the first and past the last element of a
container
vector<int> v
array_ 17
4
23
12
size_ 4
v.end()
v.begin()
31
Iterators
 One can have multiple iterators pointing to different or
identical elements in the container
vector<int> v
array_ 17
4
23
12
size_ 4
i3
i1
i2
32
Common Iterator Operations
* Return the item that the iterator currently references
++ Move the iterator to the next item in the list
-- Move the iterator to the previous item in the list
== Compare two iterators for equality
!= Compare two iterators for inequality
33
Iterators
#include <vector>
#include <cstdio>
using namespace std;
int main
{
int arr[] = { 12, 3, 17, 8 }; // standard C array
vector<int> v(arr, arr+4); //initialize vector with C array
vector<int>::iterator iter=v.begin(); //iterator for class vector
// define iterator for vector and point it to first element of v
printf(”First element of v = %dn”,*iter); // de-reference iter
iter++; // move iterator to next element
iter=v.end()-1; // move iterator to last element
}
34
Iterators
int max(vector<int>::iterator start, vector<int>::iterator end)
{
int m=*start;
while(start != end)
{
if (*start > m)
m=*start;
++start;
}
return m;
}
printf(”max of v = %d”, max(v.begin(),v.end())); 35
Iterators
vector<int> v;
for(int i=0;i<n;i++)
{
scanf(”%d”,&num);
v.push_back(num);
}
for (vector<int>::iterator i=v.begin(); i!=v.end(); i++)
// initialize i with pointer to first element of v
// i++ increment iterator, move iterator to next element
{
printf(”%d ”,*i); // de-referencing iterator returns the
// value of the element the iterator points at
}
for(i=0;i<n;i++)
printf(”%d ”,v[i]);
36
Container Adaptors
 There are a few classes acting as wrappers around
other containers, adapting them to a specific
interface
 stack – ordinary LIFO
 queue – single-ended FIFO
 priority_queue – the sorting criterion can be specified
• They are implemented using the containers seen before
- They do not provide actual data structure
• Container adapters do not support iterators
• The functions push and pop are common to all
container adapters 37
Stack Container
 They are implemented with vector, list, and deque
(by default)
 These containers restrict how elements enter and
leave a sequence
 Stack
 allows access at only one end of the sequence (top)
 Adds objects to container by pushing the object onto
the stack
 Removes objects from container by popping the stack
 LIFO ordering (last end, first out)
 Header file: <stack>
• Example of creating stacks
- A stack of int using a vector: stack < int, vector < int > > s1;
- A stack of int using a list: stack < int, list < int > > s2;
- A stack of int using a deque: stack < int > s3; 38
Queue Container
 Queue
 Allows access only at the front and rear of the sequence
 Items enter at the rear and exit from the front
 Example: waiting line at a grocery store
 FIFO ordering (first-in first-out )
 push(add object to a queue)
 pop (remove object from queue)
• Implemented with list and deque (by default)
• Header file <queue>
• Example:
- A queue of int using a list: queue <int, list<int>> q1;
- A queue of int using a deque: queue <int> q2;
39
Priority Queue Container
 Priority queue
 Operations are similar to those of a stack or queue
 Elements can enter the priority queue in any order
 Once in the container, a delete operation removes the
largest (or smallest) value
 Example: a filtering system that takes in elements and
then releases them in priority order
8
18 13
3 15
27
40
Priority Queue Container
• Priority Queues are implemented with vector (by
default) or deque
• The elements with the highest priority are removed
first
- less<T> is used by default for comparing elements
• Header file <queue>
41
Associative Containers
 In an associative container the items are not arranged
in sequence, but usually as a tree structure or a hash
table.
 The main advantage of associative containers is the
speed of searching (binary search like in a dictionary)
 Searching is done using a key which is usually a single
value like a number or string
 The value is an attribute of the objects in the container
 The STL contains two basic associative containers
 sets and multisets
 maps and multimaps
42
• Associative containers use keys to store and retrieve
elements
• There are four types: multiset, set, multimap and
map
- all associative containers maintain keys in sorted order
- all associative containers support bidirectional iterators
- set does not allow duplicate keys
- multiset and multimap allow duplicate keys
- multimap and map allow keys and values to be mapped
Associative Containers
43
Set Container
 Set
 Collection of unique values, called keys or set members
 Contains operations that allow a programmer to:
 determine whether an item is a member of the set
 insert and delete items very efficiently
5 1 3
6 27 15
Buick Ford
Jeep BMW
Set A Set B
44
Associative Containers: multiset
• Multisets are implemented using a red-black binary
search tree for fast storage and retrieval of keys
• Multisets allow duplicate keys
• The ordering of the keys is determined by the STL
comparator function object less<T>
• Keys sorted with less<T> must support comparison
using the < operator
45
Sets and Multisets
#include <set>
string names[] = {”Ole”, ”Hedvig”, ”Juan”, ”Lars”, ”Guido”};
set<string, less<string> > nameSet(names,names+5);
// create a set of names in which elements are alphabetically
// ordered string is the key and the object itself
nameSet.insert(”Patric”); // inserts more names
nameSet.insert(”Maria”);
nameSet.erase(”Juan”); // removes an element
set<string, less<string> >::iterator iter; // set iterator
string searchname;
cin >> searchname;
iter=nameSet.find(searchname); // find matching name in set
if (iter == nameSet.end()) // check if iterator points to end of set
printf(”%d not in set!”,searchname);
else
printf(”%d is in set!”,searchname); 46
Set and Multisets
string names[] = {”Ole”, ”Hedvig”, ”Juan”, ”Lars”,
”Guido”, ”Patric”, ”Maria”, ”Ann”};
set<string, less<string> > nameSet(names,names+7);
set<string, less<string> >::iterator iter; // set iterator
iter=nameSet.lower_bound(”K”);
// set iterator to lower start value ”K”
while (iter != nameSet.upper_bound(”Q”))
cout << *iter++ << endl;
// displays Lars, Maria, Ole, Patric
47
Maps and Multimaps
 A map stores pairs <key, value> of a key object and
associated value object.
 The key object contains a key that will be searched
for and the value object contains additional data
 The key could be a string, for example the name of
a person and the value could be a number, for
example the telephone number of a person
48
Maps and Multimaps
#include <map>
string names[]= {”Ole”, ”Hedvig”, ”Juan”, ”Lars”, ”Guido”, ”Patric”,
”Maria”, ”Ann”};
int numbers[]= {75643, 83268, 97353, 87353, 19988, 76455,
77443,12221};
map<string, int, less<string> > phonebook;
map<string, int, less<string> >::iterator iter;
for (int j=0; j<8; j++)
phonebook[names[j]]=numbers[j]; // initialize map phonebook
for (iter = phonebook.begin(); iter !=phonebook.end(); iter++)
cout << (*iter).first << ” : ” << (*iter).second << endl;
cout << ”Lars phone number is ” << phonebook[”Lars”] << endl;
49
Algorithms
 Implement simple, or not-so-simple loops on
ranges
 copy, find, but also partition, sort, next-permutation
 Specify their need in terms of iterator categories
 They do not care about the exact class
 Must pay attention to the iterators provided by
containers
 Often exist in several versions
 One uses default comparison, user-defined value
 Other calls user-provided predicate, function
 Some impose requirement on the data
 binary_search needs sorted data
Tip: swap(c1,c2) would swap c1 and c2 irrespective of their
data type 50
Fill and Generate
• fill(iterator1, iterator2, value);
 fills the values of the elements between iterator1 and iterator2
with value
• fill_n(iterator1, n, value);
 changes specified number of elements starting at iterator1 to
value
• generate(iterator1, iterator2, function);
 similar to fill except that it calls a function to return value
• generate_n(iterator1, n, function)
 same as fill_n except that it calls a function to return value
51
Comparing sequences of values
• bool equal(iterator1, iterator2, iterator3);
- compares sequence from iterator1 to iterator2 with the sequence
beginning at iterator3
- return true is they are equal, false otherwise
• pair mismatch(iterator1, iterator2, iterator3);
- compares sequence from iterator1 to iterator2 with the sequence
starting at iterator3
- returns a pair object with iterators pointing to where mismatch
occurred
- example of the a pair object
pair <<vector>::iterator, <vector>::iterator> par_obj;
52
Removing elements from containers
• iterator remove(iterator1, iterator2, value);
- removes all instances of value in a range iterator1 to iterator2
- does not physically remove the elements from the sequence
- moves the elements that are not removed forward
- returns an iterator that points to the "new" end of container
• iterator remove_copy(iterator1, iterator2, iterator3,
value);
- copies elements of the range iterator1-iterator2 that are not equal to
value into the sequence starting at iterator3
- returns an iterator that points to the last element of the sequence
starting at iterator3
53
Replacing elements (1)
• replace( iterator1, iterator2, value, newvalue );
replaces value with newvalue for the elements located in the range
iterator1 to iterator2
• replace_if( iterator1, iterator2, function, newvalue );
replaces all elements in the range iterator1-iterator2 for
which function returns true with newvalue
54
Replacing elements (2)
• replace_copy( iterator1, iterator2, iterator3, value,
newvalue );
replaces and copies elements of the range iterator1-iterator2 to iterator3
• replace_copy_if( iterator1, iterator2, iterator3,
function, newvalue );
replaces and copies elements for which function returns true where
iterator3
55
Search algorithms
• iterator find(iterator1, iterator2, value)
returns an iterator that points to first occurrence
of value
• iterator find_if(iterator1, iterator2, function)
returns an iterator that points to the first element
for which function returns true.
56
Sorting algorithms
• sort(iterator1, iterator2)
sorts elements in ascending order
• binary_search(iterator1, iterator2, value)
searches in an ascending sorted list for value using a binary
search
57
Copy and Merge
• copy(iterator1, iterator2, iterator3)
copies the range of elements from iterator1 to iterator2 into
iterator3
• copy_backward(iterator1, iterator2, iterator3)
copies in reverse order the range of elements from iterator1 to
iterator2 into iterator3
• merge(iter1, iter2, iter3, iter4, iter5)
ranges iter1-iter2 and iter3-iter4 must be sorted in ascending
order and copies both lists into iter5 in ascending order
58
Unique and Reverse order
• iterator unique(iterator1, iterator2)
- removes (logically) duplicate elements from a sorted list
- returns iterator to the new end of sequence
• reverse(iterator1, iterator2)
- reverses elements in the range of iterator1 to iterator2
59
Utility algorithms (1)
• random_shuffle(iterator1, iterator2)
randomly mixes elements in the range iterator1-
iterator2
• int count(iterator1, iterator2, value)
returns number of instances of value in the range
• int count_if(iterator1, iterator2, function)
counts number of instances for which function
returns true
60
Utility algorithms (2)
• iterator min_element(iterator1, iterator2)
 returns iterator to smallest element
• iterator max_element(iterator1, iterator2)
 returns iterator to largest element
• accumulate(iterator1, iterator2)
 returns the sum of the elements in the range
61
Utility algorithms (3)
• for_each(iterator1, iterator2, function)
 calls function on every element in range
• transform(iterator1, iterator2, iterator3, function)
 calls function for all elements in range iterator1-
iterator2, and copies result to iterator3
62
Algorithms on sets (1)
• includes(iter1, iter2, iter3, iter4)
 returns true if iter1-iter2 contains iter3-iter4.
Both sequences must be sorted
• set_difference(iter1, iter2, iter3, iter4,iter5)
 copies elements in range iter1-iter2 that do not
exist in second range iter3-iter4 into iter5
• set_intersection(iter1, iter2, iter3, iter4, iter5)
 copies common elements from the two ranges
iter1-iter2 and iter3-iter4 into iter5
63
Algorithms on sets (2)
• set_symmetric_difference(iter1, iter2, iter3, iter4, iter5)
 copies elements in range iter1-iter2 that are not in
range iter3-iter4 and vice versa, into iter5. Both sets must
be sorted
• set_union(iter1, iter2, iter3, iter4, iter5)
 copies elements in both ranges to iter5. Both sets must
be sorted
64
For_Each() Algorithm
#include <vector>
#include <algorithm>
#include <cstdio>
void show(int n)
{
printf(”%d ”,n);
}
int arr[] = { 12, 3, 17, 8 }; // standard C array
vector<int> v(arr, arr+4); // initialize vector with C array
for_each (v.begin(), v.end(), show); // apply function show
// to each element of vector v65
Find() Algorithm
#include <vector>
#include <algorithm>
#include <cstdio>
int key;
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array
vector<int> v(arr, arr+7); // initialize vector with C array
vector<int>::iterator iter;
pritnf(”enter value :”);
scanf(”%d ”,key);
iter=find(v.begin(),v.end(),key); // finds integer key in v
if (iter != v.end()) // found the element
printf(”Element %d foundn”,key);
else
printf(”Element %d not in vector”, key);
66
Find_If() Algorithm
#include <vector>
#include <algorithm>
#include <cstdio>
Bool mytest(int n) { return (n>21) && (n <36); };
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array
vector<int> v(arr, arr+7); // initialize vector with C array
vector<int>::iterator iter;
iter=find_if(v.begin(),v.end(),mytest);
// finds element in v for which mytest is true
if (iter != v.end()) // found the element
printf(”Found %dn”,iter);
else
printf(”Not found”); 67
Count_If() Algorithm
#include <vector>
#include <algorithm>
#include <cstdio>
Bool mytest(int n) { return (n>14) && (n <36); };
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C
array
vector<int> v(arr, arr+7); // initialize vector with C
array
int n=count_if(v.begin(),v.end(),mytest);
// counts element in v for which mytest is true
printf(”found %d elementsn”, n );
68
List Container
 An STL list container is a double linked list, in which
each element contains a pointer to its successor and
predecessor.
 It is possible to add and remove elements from both
ends of the list
 Lists do not allow random access but are efficient to
insert new elements and to sort and merge lists
69
List Container
12 7 9 21 13
int array[5] = {12, 7, 9, 21, 13 };
list<int> li(array,array+5);
7 9 21
li.push_front(8);
12 7 9 21 15
li.pop_front();
12 7 9 21
li.push_back(15);
12 7 9 21 15
li.pop_back();
8
7 12 17 21 23
li.insert()
70
Insert Iterators
 If you normally copy elements using the copy algorithm you
overwrite the existing contents
#include <list>
int arr1[]= { 1, 3, 5, 7, 9 };
int arr2[]= { 2, 4, 6, 8, 10 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
list<int> l2(arr2, arr2+5); // initialize l2 with arr2
copy(l1.begin(), l1.end(), l2.begin());
// copy contents of l1 to l2 overwriting the elements in l2
// l2 = { 1, 3, 5, 7, 9 }
71
Insert Iterators
 With insert operators you can modify the behavior of the copy algorithm
 back_inserter : inserts new elements at the end
 front_inserter : inserts new elements at the beginning
 inserter : inserts new elements at a specified location
#include <list>
int arr1[]= { 1, 3, 5, 7, 9 };
int arr2[]= { 2, 4, 6, 8, 10 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
list<int> l2(arr2, arr2+5); // initialize l2 with arr2
copy(l1.begin(), l1.end(), back_inserter(l2)); // use back_inserter
// adds contents of l1 to the end of l2 = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 }
copy(l1.begin(), l1.end(), front_inserter(l2)); // use front_inserter
// adds contents of l1 to the front of l2 = { 9, 7, 5, 3, 1, 2, 4, 6, 8, 10 }
copy(l1.begin(), l1.end, inserter(l2,l2.begin());
// adds contents of l1 at the ”old” beginning of l2 = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 }
72
Sort & Merge
 Sort and merge allow you to sort and merge elements
in a container
#include <list>
int arr1[]= { 6, 4, 9, 1, 7 };
int arr2[]= { 4, 2, 1, 3, 8 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
list<int> l2(arr2, arr2+5); // initialize l2 with arr2
l1.sort(); // l1 = {1, 4, 6, 7, 9}
l2.sort(); // l2= {1, 2, 3, 4, 8 }
l1.merge(l2); // merges l2 into l1
// l1 = { 1, 1, 2, 3, 4, 4, 6, 7, 8, 9}, l2= {}
73
Functions Objects
 Some algorithms like sort, merge, accumulate can take a
function object as argument.
 A function object is an object of a template class that has a
single member function : the overloaded operator ()
 It is also possible to use user-written functions in place of
pre-defined function objects
#include <list>
#include <functional>
int arr1[]= { 6, 4, 9, 1, 7 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
l1.sort(greater<int>()); // uses function object
greater<int>
// for sorting in reverse order l1 = { 9, 7, 6, 4, 1 }
74
Function Objects
 The accumulate algorithm accumulates data over the elements
of the containing, for example computing the sum of elements
#include <list>
#include <functional>
#include <numeric>
int arr1[]= { 6, 4, 9, 1, 7 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
int sum = accumulate(l1.begin(), l1.end() , 0, plus<int>());
int sum = accumulate(l1.begin(), l1.end(),0); // equivalent
int n = accumulate(l1.begin(), l1.end() , 100, minus<int>());
75
User Defined Function Objects
class squared _sum // user-defined function object
{
public:
int operator()(int n1, int n2) { return n1+n2*n2; }
};
int sq = accumulate(l1.begin(), l1.end() , 0,
squared_sum() );
// computes the sum of squares
76
User Defined Function Objects
template <class T>
class squared _sum // user-defined function object
{
public:
T operator()(T n1, T n2) { return n1+n2*n2; }
};
vector<complex> vc;
complex sum_vc;
vc.push_back(complex(2,3));
vc.push_back(complex(1,5));
vc.push_back(complex(-2,4));
sum_vc = accumulate(vc.begin(), vc.end() ,
complex(0,0) , squared_sum<complex>() );
// computes the sum of squares of a vector of complex numbers
77

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Python Modules
Python ModulesPython Modules
Python Modules
 
2D Array
2D Array 2D Array
2D Array
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
14 file handling
14 file handling14 file handling
14 file handling
 
Stack application
Stack applicationStack application
Stack application
 
Files in c++
Files in c++Files in c++
Files in c++
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1
 
The string class
The string classThe string class
The string class
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
C functions
C functionsC functions
C functions
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
File handling in c
File handling in cFile handling in c
File handling in c
 

Andere mochten auch

Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryKumar Gaurav
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL乐群 陈
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
 
Stl Containers
Stl ContainersStl Containers
Stl Containersppd1961
 
Understanding the components of standard template library
Understanding the components of standard template libraryUnderstanding the components of standard template library
Understanding the components of standard template libraryRahul Sharma
 
14 Ordenacion
14 Ordenacion14 Ordenacion
14 OrdenacionUVM
 
The normal distribution
The normal distributionThe normal distribution
The normal distributionShakeel Nouman
 
7 Stl Y Los Contenedores Basicos 2 Parte
7 Stl Y Los Contenedores Basicos 2 Parte7 Stl Y Los Contenedores Basicos 2 Parte
7 Stl Y Los Contenedores Basicos 2 ParteUVM
 
7 Stl Y Los Contenedores Basicos 3 Parte
7 Stl Y Los Contenedores Basicos 3 Parte7 Stl Y Los Contenedores Basicos 3 Parte
7 Stl Y Los Contenedores Basicos 3 ParteUVM
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++ppd1961
 
The State of Twitter: STL 2011
The State of Twitter: STL 2011The State of Twitter: STL 2011
The State of Twitter: STL 2011Infuz
 
7 Stl Y Los Contenedores Basicos
7 Stl Y Los Contenedores Basicos7 Stl Y Los Contenedores Basicos
7 Stl Y Los Contenedores BasicosUVM
 

Andere mochten auch (20)

Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
Stl design overview
Stl design overviewStl design overview
Stl design overview
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Stl Containers
Stl ContainersStl Containers
Stl Containers
 
Understanding the components of standard template library
Understanding the components of standard template libraryUnderstanding the components of standard template library
Understanding the components of standard template library
 
Savitch ch 18
Savitch ch 18Savitch ch 18
Savitch ch 18
 
1.5.5 stl
1.5.5 stl1.5.5 stl
1.5.5 stl
 
Ada 1 bloquaade 2
Ada   1 bloquaade 2Ada   1 bloquaade 2
Ada 1 bloquaade 2
 
14 Ordenacion
14 Ordenacion14 Ordenacion
14 Ordenacion
 
The normal distribution
The normal distributionThe normal distribution
The normal distribution
 
7 Stl Y Los Contenedores Basicos 2 Parte
7 Stl Y Los Contenedores Basicos 2 Parte7 Stl Y Los Contenedores Basicos 2 Parte
7 Stl Y Los Contenedores Basicos 2 Parte
 
7 Stl Y Los Contenedores Basicos 3 Parte
7 Stl Y Los Contenedores Basicos 3 Parte7 Stl Y Los Contenedores Basicos 3 Parte
7 Stl Y Los Contenedores Basicos 3 Parte
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
The State of Twitter: STL 2011
The State of Twitter: STL 2011The State of Twitter: STL 2011
The State of Twitter: STL 2011
 
Boost C++ Libraries
Boost C++ LibrariesBoost C++ Libraries
Boost C++ Libraries
 
Algoritmo Heap Sort
Algoritmo Heap SortAlgoritmo Heap Sort
Algoritmo Heap Sort
 
7 Stl Y Los Contenedores Basicos
7 Stl Y Los Contenedores Basicos7 Stl Y Los Contenedores Basicos
7 Stl Y Los Contenedores Basicos
 
C++ Template
C++ TemplateC++ Template
C++ Template
 

Ähnlich wie STL in C++

Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxAbhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functionsSwarup Boro
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02Abdul Samee
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossumoscon2007
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingMandeep Singh
 
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docxAssg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docxfestockton
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxrohinitalekar1
 
I have question in c++ program I need the answer as soon as possible.docx
I have question in c++ program I need the answer as soon as possible.docxI have question in c++ program I need the answer as soon as possible.docx
I have question in c++ program I need the answer as soon as possible.docxdelciegreeks
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 

Ähnlich wie STL in C++ (20)

Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Op ps
Op psOp ps
Op ps
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Unit 2
Unit 2Unit 2
Unit 2
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
 
Vector3
Vector3Vector3
Vector3
 
Arrays
ArraysArrays
Arrays
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docxAssg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
I have question in c++ program I need the answer as soon as possible.docx
I have question in c++ program I need the answer as soon as possible.docxI have question in c++ program I need the answer as soon as possible.docx
I have question in c++ program I need the answer as soon as possible.docx
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 

Kürzlich hochgeladen

Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 

Kürzlich hochgeladen (20)

Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

STL in C++

  • 1. Introduction to C++ STL CodeClass[5] Disclaimer: Slides taken from various sources and modified as required
  • 2. C++ Generic Programming: Templates #include <iostream> #include <string> using namespace std; template <typename T> inline T const& Max (T const& a, T const& b) { return a < b ? b:a; } int main () { int i = 39; int j = 20; cout << "Max(i, j): " << Max(i, j) << endl; double f1 = 13.5; double f2 = 20.7; cout << "Max(f1, f2): " << Max(f1, f2) << endl; string s1 = "Hello"; string s2 = "World"; cout << "Max(s1, s2): " << Max(s1, s2) << endl; return 0; } Output: Max(i, j): 39 Max(f1, f2): 20.7 Max(s1, s2): World 2
  • 3. STL – Standard Template Library  Collections of useful classes for common data structures  Ability to store objects of any type (template)  Study of containers  Containers form the basis for treatment of data structures  Container – class that stores a collection of data  STL consists of 10 container classes:  Sequence containers  Adapter containers  Associative containers 3
  • 4. Why use STL?  STL offers an assortment of containers  STL publicizes the time and storage complexity of its containers  STL containers grow and shrink in size automatically  STL provides built-in algorithms for processing containers  STL provides iterators that make the containers and algorithms flexible and efficient.  STL is extensible which means that users can add new containers and new algorithms such that:  STL algorithms can process STL containers as well as user defined containers  User defined algorithms can process STL containers as well user defined containers 4
  • 5. Standard Template Library  The standard template library (STL) contains  Containers  Algorithms  Iterators  A container is a way that stored data is organized in memory, for example an array of elements.  Algorithms in the STL are procedures that are applied to containers to process their data, for example search for an element in an array, or sort an array.  Iterators are a generalization of the concept of pointers, they point to elements in a container, for example you can increment an iterator to point to the next element in an array 5
  • 6. Strings  In C we used char * to represent a string.  The C++ standard library provides a common implementation of a string class abstraction named string. 6
  • 7. Hello World - C #include <stdio.h> void main() { // create string ‘str’ = “Hello world!” char *str = “Hello World!”; //OR char str1[] = “Hello World!”; printf(“%sn”, str); } 7
  • 8. Hello World – C++ #include <iostream> //for cout #include <cstdio> //for printf #include <string> using namespace std; int main() { // create string ‘str’ = “Hello world!” string str = “Hello World!”; char str1[] = “Hello World!”; cout << str << endl; printf(“%s”,str1); return 0; } 8
  • 9. String  To use the string type simply include its header file. #include <string> 9
  • 10. Creating strings string str = “some text”; or string str(“some text”); other ways: string s1(7,‘a’); string s2 = s1; 10
  • 11. string length The length of string is returned by its size() operation. #include <string> string str = “something”; cout << “The size of “ << str << “is “ << str.size() << “characters.” << endl; 11
  • 12. The size method str.size() ??? In C we had structs containing only data, In C++, we have : class string { … public: … unsigned int size(); … }; 12
  • 13. String concatenation concatenating one string to another is done by the ‘+’ operator. string str1 = “Here ”; string str2 = “comes the sun”; string concat_str = str1 + str2; 13
  • 14. String comparison To check if two strings are equal use the ‘==‘ operator. string str1 = “Here ”; string str2 = “comes the sun”; if ( str1 == str2 ) /* do something */ else /* do something else */ 14
  • 15. String assignment To assign one string to another use the “=“ operator. string str1 = “Sgt. Pappers”; string str2 = “lonely hearts club bend”; str2 = str1; Now : str2 equals “Sgt. Pappers” 15
  • 17. Containers  A container is a way to store data, either built-in data types like int and float, or class objects  The STL provides several basic kinds of containers  <vector> : one-dimensional array (similar to C array, but dynamic)  <list> : double linked list  <deque> : double-ended queue  <queue> : queue  <stack> : stack  <set> : set of ordered keys  <map> : associative array (set of ordered key/value pairs) 17
  • 18. Sequence Containers  A sequence container stores a set of elements in sequence, in other words each element (except for the first and last one) is preceded by one specific element and followed by another, <vector>, <list> and <deque> are sequential containers  In an ordinary C++ array the size is fixed and can not change during run-time, it is also tedious to insert or delete elements. Advantage: quick random access  <vector> is an expandable array that can shrink or grow in size, but still has the disadvantage of inserting or deleting elements in the middle Vector should be your default choice, but choose wisely Backward compatible with C : &v[0] points to the first element 18
  • 19. Sequence Containers  <list> is a ’traditional’ double linked list (each element has points to its successor and predecessor), it is quick to insert or delete elements but has v.slow random access  <deque> is a double-ended queue, that means one can insert and delete elements from both ends, it is a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes a compromise between a <vector> and a <list> Offers random access, back and front insertion but slower than vectors, no C compatibilty 19
  • 20. Associative Containers  An associative container is non-sequential but uses a key to access elements. The keys, typically a number or a string, are used by the container to arrange the stored elements in a specific order, for example in a dictionary the entries are ordered alphabetically. Offers O(log n) insertion and access 20
  • 21. Associative Containers  A <set> stores a number of items which contain keys. The keys are the attributes used to order the items, for example a set might store objects of the class. People which are ordered alphabetically using their name  A <map> stores pairs of objects: a key object and an associated value object. A <map> is somehow similar to an array except instead of accessing its elements with index numbers, you access them with indices of an arbitrary type.  <set> and <map> only allow one key of each value, whereas <multiset> and <multimap> allow multiple identical key values 21
  • 22. Defining a new vector  Header file: <vector>  Syntax: vector<of what>  For example : vector<int> - vector of integers. vector<string> - vector of strings. vector<int * > - vector of pointers to integers. vector<Shape> - vector of Shape objects. Shape is a user defined class.  Two ways to use vector type: Array style, and STL style 22
  • 23. Operations on vector  iterator begin();  iterator end();  bool empty();  void push_back(const T& x);  iterator erase(iterator it);  iterator erase(iterator first, iterator last);  void clear();  …. 23
  • 24. Vector Container 12 7 9 21 13 int array[5] = {12, 7, 9, 21, 13 }; vector<int> v(array,array+5); v.begin(); 12 7 9 21 v.push_back(15); 12 7 9 21 15 12 7 9 21 15 v[3] 0 1 2 3 4 v.pop_back(); 24
  • 25. Vector Container vector<int> v(3); // create a vector of ints of size 3 v[0]=23; v[1]=12; v[2]=9; // vector full v.push_back(17); // put a new value at the end of array for (int i=0; i<v.size(); i++) //member function size() of vector printf(”%d ”,v[i]); // random access to i-th element 25
  • 26. Vector Container #include <vector> #include <cstdio> int arr[] = { 12, 3, 17, 8 }; // standard C array vector<int> v(arr, arr+4); // initialize vector with C array while ( ! v.empty()) // until vector is empty { printf(”%d ”, v.back() ); // output last element of vector v.pop_back(); // delete the last element } 26
  • 27. Tip : vector<bool>  Meyers: "As an STL container, there are really only two things wrong with vector<bool>. First it's not an STL containers. Second it doesn't hold bools. Other than that, there's not much to object to." (Effective STL, p79)  vector<bool> does not conform to STL requirements  it stores bools in a packed representation (e.g. bitfield)  Accessing it returns proxy objects to bools, not true bools  Use a deque<bool> or a bitset to store bools  You won't get C compatibility (but C doesn't have bools anyways) 27
  • 28. Tip : reserve()  Inserting elements may cause a memory reallocation  container is doubled in capacity  elements are copied over  Both string and vector let you increase capacity in advance through reserve()  May eliminate unnecessary reallocations  Keeps safety of dynamic data structures over C arrays  v.reserve(n)allocates memory for n objects  Distinguish capacity (memory) and size (objects)  Writing beyond the size of the container is still bad 28
  • 29. Tip : size() and empty()  You may check whether a container is empty by writing c.size() == 0 or c.empty()  However, with lists, which have a splice() function, if splice() is O(1), size() must be O(n) and conversely.  Therefore, while empty() will always run in O(1), size() may not. You should thus prefer calling empty() to checking size() against zero. 29
  • 30. vector<int> array_ Iterators  Iterators are pointer-like entities that are used to access individual elements in a container.  Often they are used to move sequentially from element to element, a process called iterating through a container. 17 4 23 12 size_ 4 vector<int>::iterator The iterator corresponding to the class vector<int> is of the type vector<int>::iterator 30
  • 31. Iterators  The member functions begin() and end() return an iterator to the first and past the last element of a container vector<int> v array_ 17 4 23 12 size_ 4 v.end() v.begin() 31
  • 32. Iterators  One can have multiple iterators pointing to different or identical elements in the container vector<int> v array_ 17 4 23 12 size_ 4 i3 i1 i2 32
  • 33. Common Iterator Operations * Return the item that the iterator currently references ++ Move the iterator to the next item in the list -- Move the iterator to the previous item in the list == Compare two iterators for equality != Compare two iterators for inequality 33
  • 34. Iterators #include <vector> #include <cstdio> using namespace std; int main { int arr[] = { 12, 3, 17, 8 }; // standard C array vector<int> v(arr, arr+4); //initialize vector with C array vector<int>::iterator iter=v.begin(); //iterator for class vector // define iterator for vector and point it to first element of v printf(”First element of v = %dn”,*iter); // de-reference iter iter++; // move iterator to next element iter=v.end()-1; // move iterator to last element } 34
  • 35. Iterators int max(vector<int>::iterator start, vector<int>::iterator end) { int m=*start; while(start != end) { if (*start > m) m=*start; ++start; } return m; } printf(”max of v = %d”, max(v.begin(),v.end())); 35
  • 36. Iterators vector<int> v; for(int i=0;i<n;i++) { scanf(”%d”,&num); v.push_back(num); } for (vector<int>::iterator i=v.begin(); i!=v.end(); i++) // initialize i with pointer to first element of v // i++ increment iterator, move iterator to next element { printf(”%d ”,*i); // de-referencing iterator returns the // value of the element the iterator points at } for(i=0;i<n;i++) printf(”%d ”,v[i]); 36
  • 37. Container Adaptors  There are a few classes acting as wrappers around other containers, adapting them to a specific interface  stack – ordinary LIFO  queue – single-ended FIFO  priority_queue – the sorting criterion can be specified • They are implemented using the containers seen before - They do not provide actual data structure • Container adapters do not support iterators • The functions push and pop are common to all container adapters 37
  • 38. Stack Container  They are implemented with vector, list, and deque (by default)  These containers restrict how elements enter and leave a sequence  Stack  allows access at only one end of the sequence (top)  Adds objects to container by pushing the object onto the stack  Removes objects from container by popping the stack  LIFO ordering (last end, first out)  Header file: <stack> • Example of creating stacks - A stack of int using a vector: stack < int, vector < int > > s1; - A stack of int using a list: stack < int, list < int > > s2; - A stack of int using a deque: stack < int > s3; 38
  • 39. Queue Container  Queue  Allows access only at the front and rear of the sequence  Items enter at the rear and exit from the front  Example: waiting line at a grocery store  FIFO ordering (first-in first-out )  push(add object to a queue)  pop (remove object from queue) • Implemented with list and deque (by default) • Header file <queue> • Example: - A queue of int using a list: queue <int, list<int>> q1; - A queue of int using a deque: queue <int> q2; 39
  • 40. Priority Queue Container  Priority queue  Operations are similar to those of a stack or queue  Elements can enter the priority queue in any order  Once in the container, a delete operation removes the largest (or smallest) value  Example: a filtering system that takes in elements and then releases them in priority order 8 18 13 3 15 27 40
  • 41. Priority Queue Container • Priority Queues are implemented with vector (by default) or deque • The elements with the highest priority are removed first - less<T> is used by default for comparing elements • Header file <queue> 41
  • 42. Associative Containers  In an associative container the items are not arranged in sequence, but usually as a tree structure or a hash table.  The main advantage of associative containers is the speed of searching (binary search like in a dictionary)  Searching is done using a key which is usually a single value like a number or string  The value is an attribute of the objects in the container  The STL contains two basic associative containers  sets and multisets  maps and multimaps 42
  • 43. • Associative containers use keys to store and retrieve elements • There are four types: multiset, set, multimap and map - all associative containers maintain keys in sorted order - all associative containers support bidirectional iterators - set does not allow duplicate keys - multiset and multimap allow duplicate keys - multimap and map allow keys and values to be mapped Associative Containers 43
  • 44. Set Container  Set  Collection of unique values, called keys or set members  Contains operations that allow a programmer to:  determine whether an item is a member of the set  insert and delete items very efficiently 5 1 3 6 27 15 Buick Ford Jeep BMW Set A Set B 44
  • 45. Associative Containers: multiset • Multisets are implemented using a red-black binary search tree for fast storage and retrieval of keys • Multisets allow duplicate keys • The ordering of the keys is determined by the STL comparator function object less<T> • Keys sorted with less<T> must support comparison using the < operator 45
  • 46. Sets and Multisets #include <set> string names[] = {”Ole”, ”Hedvig”, ”Juan”, ”Lars”, ”Guido”}; set<string, less<string> > nameSet(names,names+5); // create a set of names in which elements are alphabetically // ordered string is the key and the object itself nameSet.insert(”Patric”); // inserts more names nameSet.insert(”Maria”); nameSet.erase(”Juan”); // removes an element set<string, less<string> >::iterator iter; // set iterator string searchname; cin >> searchname; iter=nameSet.find(searchname); // find matching name in set if (iter == nameSet.end()) // check if iterator points to end of set printf(”%d not in set!”,searchname); else printf(”%d is in set!”,searchname); 46
  • 47. Set and Multisets string names[] = {”Ole”, ”Hedvig”, ”Juan”, ”Lars”, ”Guido”, ”Patric”, ”Maria”, ”Ann”}; set<string, less<string> > nameSet(names,names+7); set<string, less<string> >::iterator iter; // set iterator iter=nameSet.lower_bound(”K”); // set iterator to lower start value ”K” while (iter != nameSet.upper_bound(”Q”)) cout << *iter++ << endl; // displays Lars, Maria, Ole, Patric 47
  • 48. Maps and Multimaps  A map stores pairs <key, value> of a key object and associated value object.  The key object contains a key that will be searched for and the value object contains additional data  The key could be a string, for example the name of a person and the value could be a number, for example the telephone number of a person 48
  • 49. Maps and Multimaps #include <map> string names[]= {”Ole”, ”Hedvig”, ”Juan”, ”Lars”, ”Guido”, ”Patric”, ”Maria”, ”Ann”}; int numbers[]= {75643, 83268, 97353, 87353, 19988, 76455, 77443,12221}; map<string, int, less<string> > phonebook; map<string, int, less<string> >::iterator iter; for (int j=0; j<8; j++) phonebook[names[j]]=numbers[j]; // initialize map phonebook for (iter = phonebook.begin(); iter !=phonebook.end(); iter++) cout << (*iter).first << ” : ” << (*iter).second << endl; cout << ”Lars phone number is ” << phonebook[”Lars”] << endl; 49
  • 50. Algorithms  Implement simple, or not-so-simple loops on ranges  copy, find, but also partition, sort, next-permutation  Specify their need in terms of iterator categories  They do not care about the exact class  Must pay attention to the iterators provided by containers  Often exist in several versions  One uses default comparison, user-defined value  Other calls user-provided predicate, function  Some impose requirement on the data  binary_search needs sorted data Tip: swap(c1,c2) would swap c1 and c2 irrespective of their data type 50
  • 51. Fill and Generate • fill(iterator1, iterator2, value);  fills the values of the elements between iterator1 and iterator2 with value • fill_n(iterator1, n, value);  changes specified number of elements starting at iterator1 to value • generate(iterator1, iterator2, function);  similar to fill except that it calls a function to return value • generate_n(iterator1, n, function)  same as fill_n except that it calls a function to return value 51
  • 52. Comparing sequences of values • bool equal(iterator1, iterator2, iterator3); - compares sequence from iterator1 to iterator2 with the sequence beginning at iterator3 - return true is they are equal, false otherwise • pair mismatch(iterator1, iterator2, iterator3); - compares sequence from iterator1 to iterator2 with the sequence starting at iterator3 - returns a pair object with iterators pointing to where mismatch occurred - example of the a pair object pair <<vector>::iterator, <vector>::iterator> par_obj; 52
  • 53. Removing elements from containers • iterator remove(iterator1, iterator2, value); - removes all instances of value in a range iterator1 to iterator2 - does not physically remove the elements from the sequence - moves the elements that are not removed forward - returns an iterator that points to the "new" end of container • iterator remove_copy(iterator1, iterator2, iterator3, value); - copies elements of the range iterator1-iterator2 that are not equal to value into the sequence starting at iterator3 - returns an iterator that points to the last element of the sequence starting at iterator3 53
  • 54. Replacing elements (1) • replace( iterator1, iterator2, value, newvalue ); replaces value with newvalue for the elements located in the range iterator1 to iterator2 • replace_if( iterator1, iterator2, function, newvalue ); replaces all elements in the range iterator1-iterator2 for which function returns true with newvalue 54
  • 55. Replacing elements (2) • replace_copy( iterator1, iterator2, iterator3, value, newvalue ); replaces and copies elements of the range iterator1-iterator2 to iterator3 • replace_copy_if( iterator1, iterator2, iterator3, function, newvalue ); replaces and copies elements for which function returns true where iterator3 55
  • 56. Search algorithms • iterator find(iterator1, iterator2, value) returns an iterator that points to first occurrence of value • iterator find_if(iterator1, iterator2, function) returns an iterator that points to the first element for which function returns true. 56
  • 57. Sorting algorithms • sort(iterator1, iterator2) sorts elements in ascending order • binary_search(iterator1, iterator2, value) searches in an ascending sorted list for value using a binary search 57
  • 58. Copy and Merge • copy(iterator1, iterator2, iterator3) copies the range of elements from iterator1 to iterator2 into iterator3 • copy_backward(iterator1, iterator2, iterator3) copies in reverse order the range of elements from iterator1 to iterator2 into iterator3 • merge(iter1, iter2, iter3, iter4, iter5) ranges iter1-iter2 and iter3-iter4 must be sorted in ascending order and copies both lists into iter5 in ascending order 58
  • 59. Unique and Reverse order • iterator unique(iterator1, iterator2) - removes (logically) duplicate elements from a sorted list - returns iterator to the new end of sequence • reverse(iterator1, iterator2) - reverses elements in the range of iterator1 to iterator2 59
  • 60. Utility algorithms (1) • random_shuffle(iterator1, iterator2) randomly mixes elements in the range iterator1- iterator2 • int count(iterator1, iterator2, value) returns number of instances of value in the range • int count_if(iterator1, iterator2, function) counts number of instances for which function returns true 60
  • 61. Utility algorithms (2) • iterator min_element(iterator1, iterator2)  returns iterator to smallest element • iterator max_element(iterator1, iterator2)  returns iterator to largest element • accumulate(iterator1, iterator2)  returns the sum of the elements in the range 61
  • 62. Utility algorithms (3) • for_each(iterator1, iterator2, function)  calls function on every element in range • transform(iterator1, iterator2, iterator3, function)  calls function for all elements in range iterator1- iterator2, and copies result to iterator3 62
  • 63. Algorithms on sets (1) • includes(iter1, iter2, iter3, iter4)  returns true if iter1-iter2 contains iter3-iter4. Both sequences must be sorted • set_difference(iter1, iter2, iter3, iter4,iter5)  copies elements in range iter1-iter2 that do not exist in second range iter3-iter4 into iter5 • set_intersection(iter1, iter2, iter3, iter4, iter5)  copies common elements from the two ranges iter1-iter2 and iter3-iter4 into iter5 63
  • 64. Algorithms on sets (2) • set_symmetric_difference(iter1, iter2, iter3, iter4, iter5)  copies elements in range iter1-iter2 that are not in range iter3-iter4 and vice versa, into iter5. Both sets must be sorted • set_union(iter1, iter2, iter3, iter4, iter5)  copies elements in both ranges to iter5. Both sets must be sorted 64
  • 65. For_Each() Algorithm #include <vector> #include <algorithm> #include <cstdio> void show(int n) { printf(”%d ”,n); } int arr[] = { 12, 3, 17, 8 }; // standard C array vector<int> v(arr, arr+4); // initialize vector with C array for_each (v.begin(), v.end(), show); // apply function show // to each element of vector v65
  • 66. Find() Algorithm #include <vector> #include <algorithm> #include <cstdio> int key; int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array vector<int> v(arr, arr+7); // initialize vector with C array vector<int>::iterator iter; pritnf(”enter value :”); scanf(”%d ”,key); iter=find(v.begin(),v.end(),key); // finds integer key in v if (iter != v.end()) // found the element printf(”Element %d foundn”,key); else printf(”Element %d not in vector”, key); 66
  • 67. Find_If() Algorithm #include <vector> #include <algorithm> #include <cstdio> Bool mytest(int n) { return (n>21) && (n <36); }; int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array vector<int> v(arr, arr+7); // initialize vector with C array vector<int>::iterator iter; iter=find_if(v.begin(),v.end(),mytest); // finds element in v for which mytest is true if (iter != v.end()) // found the element printf(”Found %dn”,iter); else printf(”Not found”); 67
  • 68. Count_If() Algorithm #include <vector> #include <algorithm> #include <cstdio> Bool mytest(int n) { return (n>14) && (n <36); }; int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array vector<int> v(arr, arr+7); // initialize vector with C array int n=count_if(v.begin(),v.end(),mytest); // counts element in v for which mytest is true printf(”found %d elementsn”, n ); 68
  • 69. List Container  An STL list container is a double linked list, in which each element contains a pointer to its successor and predecessor.  It is possible to add and remove elements from both ends of the list  Lists do not allow random access but are efficient to insert new elements and to sort and merge lists 69
  • 70. List Container 12 7 9 21 13 int array[5] = {12, 7, 9, 21, 13 }; list<int> li(array,array+5); 7 9 21 li.push_front(8); 12 7 9 21 15 li.pop_front(); 12 7 9 21 li.push_back(15); 12 7 9 21 15 li.pop_back(); 8 7 12 17 21 23 li.insert() 70
  • 71. Insert Iterators  If you normally copy elements using the copy algorithm you overwrite the existing contents #include <list> int arr1[]= { 1, 3, 5, 7, 9 }; int arr2[]= { 2, 4, 6, 8, 10 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 list<int> l2(arr2, arr2+5); // initialize l2 with arr2 copy(l1.begin(), l1.end(), l2.begin()); // copy contents of l1 to l2 overwriting the elements in l2 // l2 = { 1, 3, 5, 7, 9 } 71
  • 72. Insert Iterators  With insert operators you can modify the behavior of the copy algorithm  back_inserter : inserts new elements at the end  front_inserter : inserts new elements at the beginning  inserter : inserts new elements at a specified location #include <list> int arr1[]= { 1, 3, 5, 7, 9 }; int arr2[]= { 2, 4, 6, 8, 10 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 list<int> l2(arr2, arr2+5); // initialize l2 with arr2 copy(l1.begin(), l1.end(), back_inserter(l2)); // use back_inserter // adds contents of l1 to the end of l2 = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 } copy(l1.begin(), l1.end(), front_inserter(l2)); // use front_inserter // adds contents of l1 to the front of l2 = { 9, 7, 5, 3, 1, 2, 4, 6, 8, 10 } copy(l1.begin(), l1.end, inserter(l2,l2.begin()); // adds contents of l1 at the ”old” beginning of l2 = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 } 72
  • 73. Sort & Merge  Sort and merge allow you to sort and merge elements in a container #include <list> int arr1[]= { 6, 4, 9, 1, 7 }; int arr2[]= { 4, 2, 1, 3, 8 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 list<int> l2(arr2, arr2+5); // initialize l2 with arr2 l1.sort(); // l1 = {1, 4, 6, 7, 9} l2.sort(); // l2= {1, 2, 3, 4, 8 } l1.merge(l2); // merges l2 into l1 // l1 = { 1, 1, 2, 3, 4, 4, 6, 7, 8, 9}, l2= {} 73
  • 74. Functions Objects  Some algorithms like sort, merge, accumulate can take a function object as argument.  A function object is an object of a template class that has a single member function : the overloaded operator ()  It is also possible to use user-written functions in place of pre-defined function objects #include <list> #include <functional> int arr1[]= { 6, 4, 9, 1, 7 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 l1.sort(greater<int>()); // uses function object greater<int> // for sorting in reverse order l1 = { 9, 7, 6, 4, 1 } 74
  • 75. Function Objects  The accumulate algorithm accumulates data over the elements of the containing, for example computing the sum of elements #include <list> #include <functional> #include <numeric> int arr1[]= { 6, 4, 9, 1, 7 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 int sum = accumulate(l1.begin(), l1.end() , 0, plus<int>()); int sum = accumulate(l1.begin(), l1.end(),0); // equivalent int n = accumulate(l1.begin(), l1.end() , 100, minus<int>()); 75
  • 76. User Defined Function Objects class squared _sum // user-defined function object { public: int operator()(int n1, int n2) { return n1+n2*n2; } }; int sq = accumulate(l1.begin(), l1.end() , 0, squared_sum() ); // computes the sum of squares 76
  • 77. User Defined Function Objects template <class T> class squared _sum // user-defined function object { public: T operator()(T n1, T n2) { return n1+n2*n2; } }; vector<complex> vc; complex sum_vc; vc.push_back(complex(2,3)); vc.push_back(complex(1,5)); vc.push_back(complex(-2,4)); sum_vc = accumulate(vc.begin(), vc.end() , complex(0,0) , squared_sum<complex>() ); // computes the sum of squares of a vector of complex numbers 77