- Course Home
- Online Resources
Practice Exercise #6
Implement a single C++ source file, reverse.cc that:
- Reads tokens (consecutive strings of non-whitespace characters) from standard input and puts them in order into a
Requires: cin >>, string, vector
- Invokes a template (generic) method, reverse(T &sequence) that reverses the elements in the
argument sequence. The template should take only a single type parameter (T).
Requires: C++ references, auto
- Then invokes the same reverse method to reverse the order of the characters in each token. (For example, "example" would become "elpmaxe".)
- Uses a range for to print the now reversed tokens. Separate tokens with a single space.
Requires: C++ range for; cout <<
bash$ g++ -Wall -std=gnu++0x -g -o reverse reverse.cc bash$ cat testfile.txt Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. bash$ cat testfile.txt | ./reverse .epyt hcae rof edoc eritne eht gnitaeper tuohtiw ssalc ro epyt eno naht erom ot detpada eb nac ytilanoitcnuf esohw etalpmet noitcnuf a etaerc ot su swolla sihT .sepyt cireneg htiw etarepo nac taht snoitcnuf laiceps era setalpmet noitcnuF bash$ cat testfile.txt | ./reverse | ./reverse Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.
Note that C++ likes to make copies, and that if you want to modify a data structure, say, you don't really want C++ to make a copy, modify the copy, and then throw the copy away. One way to avoid copying in C++ is to use references.
Computer Science & Engineering University of Washington Box 352350 Seattle, WA 98195-2350 (206) 543-1695 voice, (206) 543-2969 FAX