Topical Information

Here are a few questions to help you clarify your understanding of iterators.

Quiz Information

Questions

  1. iterator is to pointer as _____ is to array.

    1. string class NO
    2. vector class YES
    3. C-string NO
    4. const_iterator NO
    5. nullptr NO
  2. Given a vector of Date objects named vec, declare an iterator and initialize it to the first element of the vector.

    
            vector<Date>::iterator iter;
    
            iter = vec.begin();
    
    
  3. What is/are the difference(s) between iterator and const_iterator.

    
            A const_iterator allows access to but not change of the element it
            references.
    
            Further you can only const-iterate a constant
            vector — not iterate it.
    
    
  4. How do you translate from iterator-style positions to size_type-style positions?

    
            Just subtract the .begin() iterator from the
            iterator you are interested in.  This will give you the
            size_type distance between the two iterator positions.
    
    

    What about the other direction? How do you turn a size_type-style position into an iterator-style position?

    
            Merely add the .begin() iterator to your size_type
            value to receive the 'equivalent' iterator.
    
    
  5. The vector class gives us several utility functions that are only available in iterator form — not size_type like the string class. What are they?

    
        
    1. .begin()/.end()
    2. .rbegin()/.rend()
    3. .erase() (there are two versions, can you remember them?)
    4. .insert() (there are two versions, can you remember them?)
    5. .assign() (what were those arguments again?)
    6. construction from an iterator range (or even pointer range!)
  6. Given that we want to store the value 'q' into the element iterated by iter, show how to safely accomplish this. (Oh, iter is currently iterating into the string class object str...should that prove useful.)

    
            if (iter != str.end())
            {
                *iter = 'q';
            }
    
    
  7. Show code to initialize a constant vector object of base type char with the vowels. (Note, you won't be able to use a sequence of push_backs!)

    
            const string vowels = "aeiou";
            const vector<char> Vowels(vowels.begin(), vowels.end());
    
        OR:
    
            const char vowels[6] = "aeiou";
            const vector<char> Vowels(vowels, vowels+5);