290 likes | 595 Views
Beginning C++ Through Game Programming, Second Edition. by Michael Dawson. Chapter 4. The Standard Template Library : Hangman. Objectives. Use vectors to work with sequences Use vector member functions to manipulate sequence elements Use iterators to move through sequences
E N D
Beginning C++ Through Game Programming, Second Edition by Michael Dawson
Chapter 4 • The Standard Template Library: Hangman
Objectives • Use vectors to work with sequences • Use vector member functions to manipulate sequence elements • Use iterators to move through sequences • Use library algorithms to work with groups of elements • Plan your programs with pseudocode
The Standard Template Library (STL) • Powerful collection of code at your disposal • Facilities for storing, manipulating and retrieving data • Provides containers, algorithms, and iterators
Vectors • One kind of container provided by the STL • A dynamic array—can grow and shrink in size as needed • Member functions to manipulate elements • All of the functionality of an array plus more
Preparing to Use Vectors • All STL components live in the std namespace • Have to include the file that contains definition: • #include <vector>
Declaring a Vector • Declare vector to hold string objects • vector<string> inventory; • Declare vector to hold string objects, starting size 10 • vector<string> inventory(10); • Declared vector with size 10, all elements initialized to "nothing" • vector<string> inventory(10, "nothing"); • Declare vector and initialize it with the contents of another vector, myStuff • vector<string> inventory(myStuff);
Useful Vector Member Functions • push_back()—Adds a new element to the end of a vector • size()—Returns the size of a vector • pop_back()—Removes the last element of a vector and reduces the vector size by one • clear()—Removes all of the items of a vector and sets its size to 0 • empty()—Returns true if the vector is empty; otherwise, it returns false. • insert()—Inserts a new element into a vector • erase()—Removes an element from a vector
Indexing Vectors • Just as with arrays, can index vectors by using the subscripting operator • Display all elements: • for (int i = 0; i < inven.size(); ++i) • cout << inven[i] << endl; • Replace the hero’s first item: • inven[0] = "battle axe"; • Can’t increase a vector’s size with subscripting operator; to add a new element at the end of a vector, use push_back().
Iterators • Identify particular element in a sequence • Can access or change the value of an element • Key to using containers to their fullest • Use them to move through a sequence container • Some parts of the STL require iterators
Declaring Iterators • Generic declaration: • container-type<object-type>::iterator iterVar; • Declare an iterator named myIterator for a vector that can contain string objects: • vector<string>::iterator myIterator; • Declare constant iterator ("read-only" access): • vector<string>::const_iterator iter;
begin() Vector Member Function • begin()—Returns an iterator that refers to a container’s first element
end() Vector Member Function • end()—Returns an iterator one past the last element in a container
Iterating Through a Vector • for (iter = inventory.begin(); • iter != inventory.end(); • ++iter) • cout << *iter << endl; • begin()—Returns an iterator that refers to first element of inventory • end()—Returns an iterator one past the last element of inventory • ++iter—Increments iter, which moves it to the next element in inventory • *iter—Dereferences iter, returns the value it refers to
Accessing Values Through an Iterator • *myIterator = "battle axe"; • Alter values to which myIterator refers • myIterator does not change • Calls the size() method of the element myIterator refers to • cout << (*myIterator).size(); • Same functionality ("syntactic sugar") • cout << myIterator->size();
Algorithms • Manipulate elements in containers through iterators • Searching, sorting, copying and more • Generic—The same algorithm can work with elements of different container types • To use, include the file with their definitions: • #include <algorithm> • Algorithms (like all STL components) live in the std namespace • Can work with some containers defined outside of the STL (like string objects)
Useful Algorithms • find()—Searches elements for a value • random_shuffle()—Randomizes order of elements • sort()—Sorts elements (in ascending order, by default)
Vector Performance • Vectors (and other STL containers) are incredibly efficient • But containers have their strengths and weaknesses • Pick the right container for the job
Vector Growth • When vectors grow beyond current size, vector might be copied to new area of memory • However, reallocation might not occur at a performance-critical part of your program • With small vectors, the reallocation cost might be insignificant
Vector Capacity • Capacity not the same as size; it's how many elements a vector can hold until reallocation. • capacity()—Returns the number of elements that a vector can hold before a reallocation • reserve()—Increases the capacity of a vector • Don’t obsess over performance
Vector Strengths and Weaknesses • push_back() and pop_back() member functions are extremely efficient • But insert() and erase() can require more work • Another STL container, list, allows for efficient insertion and deletion, regardless of the sequence size • Just because you want to insert or delete elements from the middle of a sequence doesn’t mean you should abandon the vector
Pseudocode • Planning non-trivial programs can save much time and heartache • Pseudocode is a language that falls somewhere between English and a formal programming language; useful for sketching out programs. • Pseudocode example: • If you can think of a new and useful product • Then that’s your product • Otherwise • Repackage an existing product as your product • Make an infomercial about your product • Show the infomercial on TV • Charge $100 per unit of your product • Sell 10,000 units of your product
Stepwise Refinement • Taking complex steps in pseudocode and breaking them down into a series of simpler steps • Plan becomes closer to programming code • Make an infomercial becomes: • Write a script for an infomercial about your product • Rent a TV studio for a day • Hire a production crew • Hire an enthusiastic audience • Film the infomercial
Summary • The Standard Template Library (STL) is a powerful collection of programming code that provides containers, algorithms, and iterators • Containers are objects that let you store and access collections of values of the same type • Algorithms can be used with containers and provide common functions for working with groups of objects • Iterators are objects that identify elements in containers and can be manipulated to move among elements • To get the value referenced by an iterator, you can dereference the iterator using the dereference operator (*)
Summary (cont.) • A vector is one kind of sequential container provided by the STL (like dynamic array) • Very efficient to iterate through a vector • Very efficient to insert or remove an element from the end of a vector • It can be inefficient to insert or delete elements from the middle of a vector, especially if the vector is large • Pseudocode, which falls somewhere between English and a programming language, is used to plan programs • Stepwise refinement is a process used to rewrite pseudocode to make it ready for implementation