You are on page 1of 9

COMP2006

C++ Programming
Lecture 10 demo
Dr Chao Chen

1
Demo and questions time

2
Demo
• For each loop
• References

3
For-each loops

overloading

4
Container classes
• Container classes in C++ are like Java
Collection classes
• Container classes support Iterators
• Iterators are template classes
– So are the collection classes themselves
vector<string> vstr(10);
vector<string>::iterator p1 = vstr.begin();
for ( ; p1 != vstr.end(); p1++) // ++ op
cout << *p1; // * operator

5
Range based for loop
• New for-loop version for anything with ranges
• Needs iterator to exist, with begin, end and ++
for ( <type> <variable> : <container> )
• Example:
vector<int> vec1(20), vec2(20);

for ( int i : vec1 ) // Not a reference


i++;
for ( int& i : vec2 ) // References!
i++;

6
Foreach works with arrays too
int arr[] = { 11, 22, 33, 44 };

for (int x : arr)


cout << x << endl;

for (int x : arr)


cout << x << endl;
for (int& x : arr) // Reference!
x += 1; 7
Similarly with an array
int a[4] = { 5,6,7 };

for ( const int& i : a )


cout << i << " ";
cout << endl;

for ( const int& i : { 1,2,3,4 } )


cout << i << " ";
cout << endl; 8
Tasks
• You should have your Hangman part 2
code to play with and complete
• If not create a vector of strings and add
some words to it
• Write some for loops which will do the
following:
– Find all words starting with a, b or c
– Replace every ‘a’ in every word with a ‘e’
• Try using the for-each loop, the iterator
and the normal for loop with array index [] 9

You might also like