Vectors

Document Sample
Vectors Powered By Docstoc
					         Vectors


Briana B. Morrison
Adapted from Alan Eugenio
Topics
   STL Overview
   Arrays vs. Vectors
   Vectors
       APIs
       Examples
       Implementation
   Applications
       InsertionSort
       High Precision Arithmetic

                             Vectors   2
Standard Template Library

        Consists of three parts
    1.    Containers
    2.    Iterators
    3.    Algorithms




                            Vectors   3
Standard Library Containers




                 Vectors      4
Container Types
  Sequence     Adapter          Associative
  Containers   Containers       Containers

  Vector       Stack            Set, Multiset

                                Map,
  Deque        Queue
                                Mutltimap

  List         Priority Queue


                  Vectors                       5
  Sequence Containers

 A sequence container stores data by position in linear
     order 1st element, 2nd element, and so forth.

                      Sequence Container



Position 0   Position 1   Position 2       Position 3   Position 4




                             Vectors                          6
Associative Containers

   Associative containers store elements by key.
       Ex: name, social security number, or part
        number.
   A program accesses an element in an
    associative container by its key, which may
    bear no relationship to the location of the
    element in the container.



                            Vectors                 7
Adapter Classes

   An adapter contains a sequence container as
    its underlying storage structure.

   The programmer interface for an adapter
    provides only a restricted set of operations
    from the underlying storage structure.




                         Vectors                   8
     The List Container
         next          next               next          next




 front                                                             rear
                   Inserting into a List Container
          Before                                        After
 3       12        6     4                       3   12      6              4

front                                       front
                                                        15

                                Vectors                                   9
   Stack Containers
 A stack allows access at only one end of the sequence,
                     called the top.
                                                  C
                C                   top
                B   top       B               B       top           B
     A   top    A             A               A                 A        top
Push A    Push B     Push C           Pop C             Pop B
              (a)                                      (b)




                          Vectors                                   10
Queue Containers
A queue is a container that allows access only at the
          front and rear of the sequence.

A   B   C      D                              B   C    D   E

            Insert    E                A      Delete
                     rear             front




                            Vectors                        11
   Priority Queue Containers
A priority queue is a storage structure that has restricted
access operations similar to 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.               Value = 8

                         18                  13

                           3            15


                                 27


                              Vectors                  12
   Set Containers
A set is a collection of unique values, called keys or set
members.
               Set A                     Set B

          5            1              Buick   BMW
                 3                    Ford    Jaguar
          27         15               Honda   Jeep



                            Vectors                    13
Map Containers
A map is a storage structure that implements a key-
                value relationship.

 Index                            Part#   Price   Vendor
 A29-468                     D7B-916      4.95     M irage
D7B-916                      W91-A83      12.50   Calloway
W91-A83                      A29-468      8.75     M artin




                        Vectors                              14
Template Container Classes
   A template container class is a class that stores and
    processes a collection of information.
   The type of this information is a parameter that is
    specified when the template class is instantiated.
   Example:
      template<typename T>
        class some_container { … }
   The parameter T is a placeholder for
    the actual data type.
      some_container<Item_Type> call_lengths; // holds
        Item_Type
      Some_container<People> people; // holds People


                            Vectors                     15
Common Requirements for Containers
typedefs                                Meaning
value_type                              The type of the object stored in the container.
iterator                                An iterator appropriate for the container.
const_iterator                          A const_iterator appropriate for the container
Constructors                            Purpose
X()                                     Default constructor where X is the container type.
X(a)
                                        Copy constructor where X is the container type and a is
                                        an object of this type.
Functions                               Behavior
~X()                                    Destructor
X& operator=(const X& a)                Assignment operator
bool operator==(const X& a) const       Equality operator
bool operator!=(const X& a) const       Negation of equals
bool operator<(const X& a) const
bool operator>(const X& a) const        Comparison operators. Compares each item in the two
bool operator<=(const X& a) const       containers. Objects must implement < operator.
bool operator>=(const X& a) const
void swap(X& a)                         Swap the contents of this container with the other.
iterator begin()
const_iterator() begin() const          Return an iterator to the beginning of the container
iterator end()
const_iterator end() const              Return an iterator to one past the end of the container
size_t size() const                     Return the number of objects in the container
bool empty() const                      Returns true if the container is empty.



                                    Vectors                                                       16
Common Requirements for Sequences
Constructors                                 Purpose
X(size_t num, const Item_Type& initial)
                                             Constructs the container of type X containing num
                                             copies of initial.
                                             Constructs the container of type X containing a copy of
X(const_iterator start, const_iterator stop) the items starting with the object referenced by start
                                             and continuing up to but not including stop.
Functions                                    Behavior
iterator insert(iterator pos,                Insert a copy of item into the container before position
  const Item_Type& item)                     pos. Return an iterator referencing the inserted object.
iterator erase(iterator pos)
                                             Remove the item referenced by the iterator at pos.
                                             Returns an iterator to the item following pos.
Item_Type& front()
const Item_Type& front() const               Returns a reference to the first item in the container.
Item_Type& back()
const Item_Type back() const                        Returns a reference to the last item in the container
void push_back(const Item_Type& item)               Insert a new item as the last item in the container.
void pop_back()                                     Remove the last item from the container




                                                Vectors                                                     17
Requirements Applicable to
Some Sequences
Functions                        Behavior                                               Required by
void push_front(const
                                 Insert a new item as the first item in the container   list, deque
Item_Type& item)
void pop_front()                 Remove the first item from the container               list, deque
Item_Type&
operator[](size_t index)         Randomly access an item in the container via an        vector, deque
const Item_Type&                 index.
operator[](size_t index) const
Item_Type&                       Randomly access an item in the container via an
at(size_t index)
                                 index. If the index is out of bounds (>= size())       vector, deque
const Item_Type&
at(size_t index) const           throw invalid argument exception.




                                             Vectors                                                  18
The algorithm library

   The standard library header <algorithm>
    defines several template functions.
   These perform fairly standard operation on
    sequences within containers
       find an item (find)
       apply a function to each item (for_each)
       copy values from one container to another (copy)
       sort the contents of a container (sort)


                            Vectors                        19
Why use algorithm library

   Most of the algorithms in <algorithm> are
    fairly simple.
   Why not code them in-line in your program
    yourself?
       No need to “reinvent the wheel”
       While they are fairly simple, they have all been
        thoroughly tested.
       Compiler can generate more optimal code from
        standard library

                             Vectors                       20
Selected Members of <algorithm>
Function                                   Behavior
template<typename II, typename F>          Applies the function fun to each
  F for_each(II first, II last, F fun)
                                           object in the sequence. The function
                                           fun is not supposed to modify its
                                           argument. The iterator argument
                                           II is required to be an input iterator.
                                           This means that the sequence is
                                           traversed only once.
template<typename II, typename T>          Finds the first occurrence of target
  II find(II first, II last, T target)
                                           in the sequence. If not found, last is
                                           returned.
template<typename II, typename P>          Finds the first occurrence of an item
  II find_if(II first, II last, P pred)
                                           in the sequence for which function
                                           pred returns true. If not found, last
                                           is returned.
template<typename FI>                      Finds the min/max element in the
  FI min_element(FI first, FI last);
template<typename FI>                      sequence first..last. FI is a
  FI max_element(FI first, FI last)        forward iterator.


                                 Vectors                                             21
Function                                              Behavior
template<typename II, typename OI>            Copies the sequence first..last
  OI copy(II first, II last, OI result)
                                              into result..(result + (last -
                                              first)). II is an input iterator, and
                                              OI is an output iterator.
template<typename II, typename OI,            Applies op to each element of the
typename OP>
  OI transform(II first, II last, OI          sequence first..last and places
result, OP op)                                the result in result..(result +
                                              (last - first)).
template<typename II1, typename               Applies bin_op to each pair of
II2,typename OI, typename BOP>
  OI transform(II1 first1, II1 last1,         elements of the sequences
II2 first2, OI result, BOP bin_op)            first1..last1 and
                                              first2..(first2 + (last1 -
                                              first1)) and places the result in
                                              result..(result + (last1 -
                                              first1))
template<typename T>                          Exchanges the contents of a and b.
  void swap(T& a, T& b)
template<typename FI1, typename FI2>          Exchanges the values referenced by
  void iter_swap(FI1 a, FI1 b)
                                              iterators a and b.
template<typename BI>                         Reverses the sequence first..last.
  void reverse(BI first, BI last)
                                              BI is a bidirectional iterator.


                                    Vectors                                        22
Function                                              Behavior
template<typename RI>                         Randomly rearranges the contents of
  void random_shuffle(RI first, RI last)
                                              first..last. RI is a random-access
                                              iterator.
template<typename RI>                         Sorts the contents of first..last
  void sort(RI first, RI last)
                                              based on the less-than operator
                                              applied to pairs of elements.
template<typename RI, typename COMP>          Sorts the contents of first..last
  void sort(RI first, RI last,
  COMP comp)                                  based on the binary operator COMP (a
                                              function operator). COMP is a function
                                              class that takes two arguments and
                                              returns a bool.
template<typename II, typename T>             Computes init plus the sum of the
  T accumulate(II first, II last,
  T init)                                     elements in first..last. Note that
                                              this function is defined in the header
                                              <numeric>.
template<typename II1, typename II2>          Compares each element in the
  bool equal(II1 first1, II1 last1, II2
first2);                                      sequence first1..last1 to the
template<typename II1, typename II2,          corresponding elements in the
         typename BP)                         sequence first2..first2 +
  bool equal(II1 first1, II1 last2, II2
first2, BP pred)                              (last1 - first1). If they are all
                                              equal, then this returns true. The
                                              second form uses the function object
                                              pred to perform the comparison.
                                    Vectors                                       23
Onto our first container….

   The first container we will study is the vector
    container
       A sequence container
   The vector is much like the ArrayList class
    from Java
   Replaces standard arrays




                           Vectors                    24
 C++ Arrays
An array is a fixed-size collection of values of the
same data type.
An array is a container that stores the n (size)
elements in a contiguous block of memory.

     arr[0]    arr[1]   arr[2]        ...       arr[n-1]
         0       1         2                       n-1




                          Vectors                        25
Evaluating an Array as a Container
   The size of an array is fixed at the time of its
    declaration and cannot be changed during the
    runtime.
       An array cannot report its size. A separate integer variable
        is required in order to keep track of its size.
   C++ arrays do not allow the assignment of one array
    to another.
       The copying of an array requires the generation of a loop
        structure with the array size as an upper bound.
   C++ arrays sometimes allow out of bounds access



                                 Vectors                            26
 Vectors



v[0]   v[1]   v[2]   ...             v[n-1]   room to grow

 0       1     2                      n-1




                           Vectors                           27
What is a Vector?

    A vector is a finite sequence of items such
     that:
    1. Given any index, the item in the sequence at that
       index can be accessed or modified in constant
       time.
    2. An insertion or deletion at the back of the
       sequence takes only constant time, on average.




                           Vectors                     28
Vectors – “Smart” Arrays
    The vector class is a “smart” array:
1.   Random access is supported with the index
     operator, [ ]
2.   There is a size method to keep track of the number
     of items
3.   Re-sizing is automatic
4.   There are methods to insert and delete at any
     position
5.   There is an assignment operator to copy one
     vector to another
6.   The vector class is templated, so you can restrict
     the type of items for a vector container
7.   Vectors are as efficient as arrays.

                          Vectors                     29
YOU MAY NEVER

WANT TO USE AN

ARRAY AGAIN!!!
       Vectors   30
Storage Containers (Vectors)

   A vector has all of the nice indexing features
    of an array along with the ability to
    dynamically grow to meet demand.
     // output elements of v
     for (i = 0; i < v.size(); i++)
        cout << v[i] << " ";
     Output: 7 4 9 3 1



                             Vectors                 31
Storage Containers (Vectors)
   A vector is a "super-array“, meaning all
    familiar array algorithms work.
   You also have the freedom to to grow or
    shrink it.
           vector v (with 5 elements)
             7     4  9     3   1
           v.resize (8); (grow to 8 elements)
              7    4     9   3     1    0   0     0
           v.resize (3); (shrink to 3 elements)
              7    4     9

                        Vectors                   32
Storage Containers (Vectors)

   Vectors allow for direct access to their
    elements through an index, but are not
    efficient storage structures for:
       insertion of items at arbitrary positions in a list.
       deletion of items at arbitrary positions in a list.

                     15 20 30 35 40               15 20 30 35 40
                             25
                     15 20        30 35 40        15        30 35 40
                                                       20




                                        Vectors                        33
Vector APIs

   Following is a brief introduction to the APIs of
    the vector class with examples.




                         Vectors                   35
CLASS vector          Constructors                <vector>
 vector();
  Create an empty vector. This is the default
  constructor.

 vector(int n, const T& value = T());
  Create a vector with n elements, each having a
  specified value. If the value argument is omitted, the
    elements are filled with the default value for type T.
    Type T must have a default constructor, and the
    default value of type T is specified by the notation
  T().




                           Vectors                    36
Declaring Vector Objects
  // empty vector of doubles;
  vector<double> dblVector;

 // vector of size 10; each element
 // contains the empty string
 vector<string> strVector(10);

 // vector of size 5 containing the integer
 // value 99
 vector<int> intVector(5,99);


                    Vectors               37
CLASS vector          Constructors                <vector>
 vector(T *first, T *last);
  Initialize the vector using the address range [first,
  last). The notation *first and *last is an example of
  pointer notation that we cover later in the course.




                           Vectors                    38
Declaring Vector Objects
  // array of size 5 with initial values;
  // vector contains copies of array values

int arr[5] = {9, 2, 7, 3, 12};
vector<int> v(arr,arr+5);



     9           2            7      3   12
      0           1            2     3    4

                           Vectors            39
CLASS vector           Operations                <vector>
 T& back();
  Return the value of the item at the rear of the vector.
    Precondition: The vector must contain at least one
                  element.

 const T& back() const;
   Constant version of back().

 bool empty() const;
  Return true if the vector is empty and false
  otherwise.


                          Vectors                    40
Using Back and Empty
int arr[5] = {9, 2, 7, 3, 12};
vector<int> v(arr,arr+5);

cout << v.back( );
v.back( ) = 99;
If (v.empty( )) cout << “Empty”);


     9          2            7       3   12
      0          1            2      3    4
                           Vectors            41
CLASS vector           Operations                <vector>
 T& operator[ ] (int i);
  Allow the vector element at index i to be retrieved or
    modified.
    Precondition: The index, i, must be in the range 0
                        i < n, where n is the number of
                       elements in the vector.
    Postcondition: If the operator appears on the left
                    side of an assignment statement,
                    the expression on the right side
                    modifies the element referenced by
                       the index.

 const T& operator[ ] (int i) const;
   Constant version of the index operator.
                          Vectors                    42
Using [ ] Operators
int arr[5] = {9, 2, 7, 3, 12};
vector<int> v(arr,arr+5);

cout << v[4];
v[1] = 88;



     9          2            7       3   12
      0          1            2      3    4
                           Vectors            43
Using [ ] Operators

vector<int> emptyV;

cout << emptyV[4]; // prints bad memory
emptyV[1] = 88;    // error, no memory allocated




                       Vectors                     44
CLASS vector            Operations                  <vector>
 void resize((int n, const T& fill = T());
   Modify the size of the vector. If the size is increased,
     the value fill is added to the elements on the tail of
     the vector. If the size is decreased, the original
     values at the front are retained.
     Postcondition: The vector has size n.

 int size() const;
   Return the number of elements in the vector.




                            Vectors                    45
Resizing a Vector
int arr[5] = {7, 4, 9, 3, 1};
vector<int> v(arr,arr+5);
                        // v initially has 5
integers
v.resize(10);// list size is doubled
v.resize(4); // list is contracted. data
                        // is lost
             vector<int> v(arr,5)
              7     4       9   3     1

            v.resize(10);

              7     4       9   3     1       0   0   0   0   0

            v.resize(4);

               7    4       9   3




                                    Vectors                       46
CLASS vector           Operations                 <vector>
 void push_back(const T& value);
   Add a value at the rear of the vector.
     Postcondition: The vector has a new element at
                    the rear and its size increases by 1.

 void pop_back();
   Remove the item at the rear of the vector.
     Precondition: The vector is not empty.
     Postcondition: The vector has a new element at
                    the rear or is empty.



                           Vectors                    48
Adding and Removing Vector Elements
          v.size() = 4                          v.size() = 5

  12     -5       8   14                12    -5     8   14    10
   0      1       2      3              0       1    2     3    4
          Before                             After v.push_back(10)


  v.size() = 2                           v.size() = 1
  4.6     6.8                                  4.6
   0          1                                0
       Before                          After v.pop_back()

                             Vectors                                49
Output with Vectors
// number of elements in list is v.size()
template <classname T>
void writeVector(const vector<T>& v)
{
    // capture the size of the vector in n
    int i, n = v.size();

    for(i = 0; i < n; i++)
      cout << v[i] << " ";
    cout << endl;
}
                     Vectors                 50
Test Yourself

1.   Declare a vector of integers
2.   Put the values 1 through 10 into the vector
3.   Print out the size of the vector
4.   Change the last value of the vector to the
     value 99
5.   Erase the last 2 values in the vector
6.   Resize the vector to contain 100 values


                        Vectors                    51
AN ITERATOR IS AN OBJECT THAT
ENABLES A USER TO LOOP THROUGH
A CONTAINER WITHOUT VIOLATING
THE PRINCIPLE OF DATA
ABSTRACTION.



               Vectors          52
1. START AT THE BEGINNING OF THE
   CONTAINER;
2. ADVANCE TO THE NEXT ITEM IN
   THE CONTAINER;
3. DETERMINE WHEN NO MORE LOOP
   ITERATIONS ARE POSSIBLE;
4. RETURN THE ITEM WHERE THE
 ITERATOR IS NOW POSITIONED.
              Vectors            53
    Declaring Iterators
   Most container classes (including vector) have a
    nested iterator class.

   To declare an iterator:
       vector<int>::iterator vectorIter;
       vector<string>::iterator iter;
   These are two distinct types and are not
    compatible.


                         Vectors                  54
CLASS vector                   Operations               <vector>

iterator begin();
   Returns an iterator that references the first position
   (0) of the list. If the vector is empty, the iterator value
   end() is returned.

iterator end();
   Returns an iterator that signifies a location immediately
   out of the range of actual elements. A program must
   not dereference the value of end() with the * operator.




                              Vectors                       55
Using Iterators
   vector<int> v;
   for (int i = 1; i <= 100; i++ )
          v.push_back(i);
   vector<int>::iterator vectorIter;
   vectorIter = v.begin(); //initialize
   vectorIter = v.end();       //past end of list




                        Vectors                     56
CLASS vector                Operations              <vector>
void erase(iterator pos);
  Erase the element pointed to by pos.
  Precondition:    The vector is not empty.
  Postcondition: The vector has one fewer element.

void erase(iterator first, iterator last);
  Erase all list elements within the iterator range [first,
  last].
  Precondition:     The vector is not empty.
  Postcondition: The vector decreases by the number
                     of elements in the range.

                            Vectors                     57
 Using Iterators
vector<int> v;
for (int i = 1; i <= 100; i++ )
       v.push_back(i);
vector<int>::iterator vectorIter;
v.erase ( v.begin() );
v.erase ( v.end() );            // ERROR
v.erase( v.begin(), v.end() );



                         Vectors           58
CLASS vector                Operations              <vector>
iterator insert(iterator pos, const T& value);
   Insert value before pos, and return an iterator pointing
   to the position of the new value in the vector. The
   operation does not affect any existing iterators.
   Postcondition: The vector has a new element.




                            Vectors                     59
 Using Iterators
vector<int> v;
for (int i = 1; i <= 100; i++ )
       v.push_back(i);
vector<int>::iterator vectorIter;
v.insert ( v.begin(), 255 );
v.insert ( v.end(), 777 );




                          Vectors   60
CLASS vector::iterator           Operations                   <vector>
*:   Accesses the value of the item currently pointed to by the
     iterator.
          *iter;
++ : Moves the iterator to the next item in the vector.
         iter++;
-- : Moves the iterator to the previous item in the vector.
         iter--;
== : Takes two iterators as operands and returns true when they
     both point at the same item in the vector.
         iter1 == iter2
!= : Returns true when the two iterators do not point at the same
     item in the vector.
         iter1 != iter2

                                 Vectors                          61
 Using Iterators
vector<int> v;
for (int i = 1; i <= 100; i++ )
        v.push_back(i);
vector<int>::iterator vectorIter;
vectorIter = v.end();             //past end of list
vectorIter--;                     //last element
cout << *vectorIter;
if (vectorIter != v.begin() )
        vectorIter = v.begin();
if (*vectorIter == *v.end() )     // error!
        cout << “Same elements.” << endl;

                              Vectors                  62
Program Example

   Here is a program fragment that reads in
    several words, one per line, deletes the first
    and last words read in, and prints out the
    rest:




                         Vectors                     63
                                              Input:
vector<string>words;
string word;                                  apple
                                              banana
for (int i = 0; i < 5; i++)                   candy
{                                             donut
    cin >> word;
                                              egg
    words.push_back (word);
} // reading in words
words.erase (words.begin());
words.pop_back();
for (unsigned j = 0; j < words.size(); j++)
    cout << words [j] << endl;




                        Vectors                        64
Vector Example

// Create a vector to hold
 strings.
vector<string> my_vector;
// Add some entries.
my_vector.push_back("Bashful");
my_vector.push_back("Awful");
my_vector.push_back("Jumpy");
my_vector.push_back("Happy");

                 Vectors          65
Vector Example (2)


                                           Had to slide
                                         [2],[3] to [3],[4]
 my_vector.insert(2, “Doc”);




                               Vectors                        66
 Vector Example (3)




my_vector.push_back("Dopey");            // add at end
                                Cheap to add at end




                      Vectors                            67
Vector Example (4)
 my_vector.erase(1);




                                    Had to slide [2..5] to [1..4]
 lst.set(1, “Sneezy”);




                          Replacement is cheap


                       Vectors                                 68
Example Applications of vector
vector<Item_Type> some_Item_Types;
Item_Type nums[] = {5, 7, 2, 15};
for (size_t i = 0; i < 4; i++)

 some_Item_Types.push_back(nums[i]
 );

Item_Type sum = 0;
for (size_t i = 0; i < 4; i++) {
  sum += some_Item_Types[i];
}
cout << "sum is " << sum << endl;
                Vectors              69
EXERCISE: WHAT’S THE OUTPUT?
 int a[] = {4, 7, 5, 2, 3};
 int aSize = sizeof(a) / sizeof(int);
 vector<int> vect (a, a+aSize), temp;
            // same as vect(a, a+5);

 for (int i=vect.size()-1; i >=0; i--)
     temp.push_back(vect[i]);
 vect = temp;
  write_vector(vect);




                           Vectors       70
EXERCISE: WHAT DOES THIS
TEMPLATE FUNCTION DO?
template <typename T>
void f(const vector<T>& vA, vector<T>& vB, T key)
{ int i;

    for (i = 0; i < vA.size( ); i++)
      if (vA[i] != key)
          vB.push_back(vA[i]);
}
    (A)   Inserts all n elements of vA matching key into vB.
    (B)   Inserts all n elements of vA that do not match key into vB.
    (C)   Performs the sequential search.
    (D)   Deletes every other element from vA and inserts it into vB.

                                           Vectors                      71
Application using Vectors

     Insertion Sort




           Vectors          72
The Insertion SortMonroe
            Start with
               Monroe



                    Chin   Monroe
                                      Insert Chin in location 0;
Processing Chin                      Monroe moves to location 1


                    Chin   Flores   Monroe       Insert Flores in location 1;
Processing Flores
                                                 Monroe moves to location 2



                    Chin   Flores   Monroe       Stein
Processing Stein                                         Element Stein is OK

                                                                  Insert Dare at
                                                                  location 1;
Processing Dare     Chin   Dare     Flores      Monroe    Stein
                                                                  the tail of the list
                                                                  shifts to the right

                                      Vectors                                            73
Insertion Sort Algorithm
 insertionSort():
 // sort a vector of type T using insertion
 // sort
 template <classname T>
 void insertionSort(vector<T>& v)
 {
    int i, j, n = v.size();
    T temp;

   // place v[i] into the sublist v[0] ...
   // v[i-1], 1 <= i < n, so it is in the
   // correct position

                    Vectors                  74
Insertion Sort Algorithm
   for (i = 1; i < n; i++)
   { // index j scans down list from v[i]
        // looking for correct position to
          // locate target. assigns it to
v[j]
       j = i;
       temp = v[i];
       // locate insertion point by scanning
        // downward as long as temp < v[j-1]
          // and we have not encountered the
            // beginning of the list



                      Vectors                  75
Insertion Sort Algorithm
        while (j > 0 && temp < v[j-1])
        {
            // shift elements up list to make
              // room for insertion
             v[j] = v[j-1];
             j--;
        }
        // the location is found; insert temp
        v[j] = temp;
    }
}
                       Vectors                  76
      APPLICATION


HIGH-PRECISION ARITHMETIC



           Vectors     77
IN PUBLIC-KEY CRYPTOGRAPHY, THE
INTEGERS ARE HUNDREDS OF DIGITS
LONG.

There is no data type that we can use to store
integers that are this long. We must create
one.

                     Vectors              78
WE NOW DESIGN AND IMPLEMENT A

SIMPLIFIED very_long_int CLASS.

HERE ARE THE INTERFACES FOR THE

THREE METHODS:




                Vectors           79
1. // Precondition: The input starts with a sequence of
   //               digits, followed by an ‘X’, with blanks,
   //               end-of-line markers, and invalid
   //               characters ignored. There are no
   //               leading zeroes, except for ‘0’ itself.

   // Postcondition: very_long contains the very_long_int
   //                whose digits came from instream, and
   //                a reference to instream has been
   //                returned. The worstTime(n) is O(n),
   //                where n is the number of digit
   //                characters before ‘X’ in the input.
   friend istream& operator>> (istream& instream,
                                  very_long_int& very_long);
                             Vectors                       80
FOR EXAMPLE, SUPPOSE THE INPUT
CONSISTS OF

3281V2
56X

IF WE HAVE

very_long_int very_long;

cin >> very_long;

THEN very_long WILL CONTAIN 3281256.
                           Vectors   81
2. // Postcondition: The value of very_long has been written
   //                to outstream. The worstTime(n) is O(n),
   //                where n is the size of very_long.

 friend ostream& operator<< (ostream& outstream,
                      const very_long_int& very_long);




                           Vectors                        82
3. // Postcondition: The value returned is the sum of the
   //                 calling object (the left-hand operand)
   //                 and other_very_long (the right-hand
   //                 operand).The worstTime(n) is O(n),
   //                 where n is the maximum of the number
   //                 of digits in the calling object and
   //                 other_very_long.

  very_long_int operator+ (const very_long_int&
                                    other_very_long);




                           Vectors                       83
FOR EXAMPLE, SUPPOSE THE
very_long_int OBJECTS x AND y HAVE
VALUES OF 285 AND 12396,
RESPECTIVELY. THEN

x+y

RETURNS A very_long_int OBJECT
WITH THE VALUE 12681.
                Vectors          84
Design Time

   Now that we know the “what”,

   We have to figure out the “how”:
       How do we store the information in computer
        memory?
       What happens with each operation? What will
        memory look like?




                           Vectors                    85
THE ONLY DATA IN THE very_long_int
CLASS IS


vector<char> digits;   // vector < int> digits;



THE TYPE char IS AN INTEGER TYPE,
AND TAKES UP ONLY ONE BYTE.

                        Vectors                   86
IMPLEMENTATION OF THE
very_long_int CLASS:


1. istream& operator>> (istream& instream,
                        very_long_int& very_long)

WE FIRST MAKE very_long AN EMPTY
CONTAINER, AND THEN, UNTIL ‘X’ IS
REACHED, APPEND EACH DIGIT
CHARACTER IN THE INPUT TO
very_long.
                        Vectors                     87
istream& operator>> (istream& instream,
                            very_long_int& very_long)
{
    char digit_char;
    very_long.digits.erase (very_long.digits.begin( ),
                                very_long.digits.end( ));
    do
    {
         instream >> digit_char;
         if (‘0’ <= digit_char && digit_char <= ‘9’)
              very_long.digits.push_back (digit_char – ‘0’);
    } // do
    while (digit_char != ‘X’);

     return instream;
} // overloading >>
                              Vectors                          88
ANALYSIS: WE ASSUME THE ARRAY-
BASED DESIGN OF THE vector CLASS
DESCRIBED EARLIER. FOR ANY
INTEGER n, APPENDING n DIGITS TO
THE vector OBJECT digits TAKES TIME
LINEAR IN n, EVEN IN THE WORST
CASE.



                Vectors           89
THE “FRIEND”LY OVERLOAD OF
operator<< IS STRAIGHTFORWARD:




               Vectors           90
2. ostream& operator<< (ostream& outstream,
                           const very_long_int& very_long)
   {
        for (unsigned i = 0; i < very_long.digits.size( ); i++)
              outstream << (int)very_long.digits [i];
        return outstream;
   } // overloading <<


THE CAST TO int IS NEEDED;
OTHERWISE, THE “OUTPUT” OF A char
IN THE RANGE ‘0’ … ‘9’ CAUSES AN
ACTION (SUCH AS A BACKSPACE OR
LINE FEED) TO BE PERFORMED.

                            Vectors                       91
ANALYSIS: THE vector CLASS’S INDEX
OPERATOR, operator[ ], TAKES
CONSTANT TIME, SO FOR operator<<,
worstTime(n) IS LINEAR IN n.




                Vectors          92
3. very_long_int very_long_int::operator+ (
                 const very_long_int& other_very_long)


  THE USUAL ALGORITHM FOR
  ADDITION IS FOLLOWED. FOR
  EXAMPLE, SUPPOSE WE HAVE


       6282598
     +    9175
                         Vectors                   93
THE LEAST SIGNIFICANT DIGITS, 8
AND 5, ARE ADDED. THE SUM IS 13,
SO 3 IS APPENDED TO THE digits
FIELD OF A very_long_int OBJECT sum,
AND THE CARRY IS 1.




                Vectors            94
THE NEXT-TO-LEAST SIGNIFICANT
(THAT IS, TEN’S) DIGITS, 9 AND 7,
AND THE CARRY ARE ADDED. 7 IS
APPENDED TO sum.digits, AND THE
CARRY IS 1.




                Vectors             95
WE APPEND EACH TIME BECAUSE
push_back IS FAST. BUT THEN sum
ENDS UP WITH THE DIGITS IN
REVERSE ORDER:

3771926 (NOTE: 6282598 + 9175 = 6291773)

THE GENERIC ALGORITHM reverse
PUTS sum.digits IN THE CORRECT
ORDER, AND sum IS RETURNED.
                  Vectors             96
WE WILL USE A HELPER FUNCTION,
least (unsigned i),
WHICH RETURNS THE iTH LEAST
SIGNIFICANT DIGIT IN THE CALLING
very_long_int OBJECT.




              Vectors         97
For example, suppose the calling
very_long_int object has the value 13579.
then
     least (0) RETURNS ‘9’
     least (1) RETURNS ‘7’
     least (2) RETURNS ‘5’
     least (3) RETURNS ‘3’
     least (4) RETURNS ‘1’
     least (5) RETURNS ‘0’
     least (6) RETURNS ‘0’
                   Vectors                  98
// Postcondition: If i >= digits.size( ), 0 has been
//                    returned; else the ith least significant
//                    digit in digits has been returned. The
//                    least significant digit is the 0th least
//                    significant digit.
char very_long_int::least (unsigned i) const
{
    if (i >= digits.size( ))
        return 0;
    else
        return digits [digits.size( ) – i – 1] ;
} // least




                            Vectors                       99
ANALYSIS: THE least METHOD TAKES
CONSTANT TIME.

NOW FOR THE operator+ METHOD.




               Vectors          100
very_long_int very_long_int::operator+ (const
                    very_long_int& other_very_long)
{
   unsigned carry = 0,
              larger_size,
              partial_sum;

  very_long_int sum;

  if (digits.size( ) > other_very_long.digits.size( ))
      larger_size = digits.size();
  else
      larger_size = other_very_long.digits.size( );


                          Vectors                        101
   for (unsigned i = 0; i < larger_size; i++)
   {
       partial_sum = least (i) + other_very_long.least (i)
                               + carry;
       carry = partial_sum / 10;
       sum.digits.push_back (partial_sum % 10);
   } // for

    if (carry == 1)
        sum.digits.push_back (carry);
    reverse (sum.digits.begin( ), sum.digits.end( ));
    return sum;
} // overloading +


                         Vectors                        102
ANALYSIS: THE least METHOD TAKES
CONSTANT TIME, AND APPENDING n
DIGITS TO sum.digits TAKES LINEAR-IN-
n TIME IN BOTH THE AVERAGE AND
WORST CASES.




                Vectors          103
ALSO, THE GENERIC ALGORITHM
reverse TAKES LINEAR-IN-n TIME IN
BOTH THE AVERAGE AND WORST
CASES. SO FOR operator+,
averageTime(n) AND worstTime(n) ARE
BOTH LINEAR IN n.




                 Vectors              104
HERE IS A very_long_int APPLET:


http://www.cs.lafayette.edu/~collinsw/verylongcpp/long.html




                          Vectors                      105
Design of Vector

   The following describes one possible
    implementation (Hewlett-Packard) of the
    vector class.

   The underlying storage facility is an array:
    that’s how random-access is achieved.




                         Vectors                   106
THERE ARE THREE FIELDS, ALL
POINTERS:
 start, WITH THE ADDRESS OF THE 0TH
     LOCATION IN THE ARRAY;

 finish, WHICH POINTS TO THE LOCATION
        JUST AFTER THE BACK ITEM OF THE
        VECTOR.
 end_of_storage, WHICH POINTS TO THE
      LOCATION JUST AFTER THE LAST
      LOCATION ALLOCATED FOR THE
      ARRAY.

                   Vectors                107
SUPPOSE WE HAVE
vector<double> weights (100);

weights.push_back (0.1);




HERE IS A SNAPSHOT OF MEMORY:




                      Vectors   108
    start
                 0.0   weights [0]
                 0.0   weights [1]
    finish




end_of_storage
                       weights [99]
                 0.1

                       weights[199]
                         Vectors      109
WE CAN EASILY DEFINE A FEW
METHODS:


 iterator begin( ) { return start; }

 iterator end( ) { return finish; }

 unsigned size( ) { return finish – start; }

 bool empty( ) { return start == finish; }

                         Vectors               110
IF finish != end_of_storage, THE
DEFINITION OF push_back IS EASY TO
UNDERSTAND:

JUST INCREMENT finish AND STORE
THE NEW ITEM AT THAT LOCATION.




                  Vectors          111
BUT if finish = end_of_storage,

A new array, whose capacity is twice that of
the old array is created.

Then the old array’s items are copied to the
new array, and the new array (pointer) is
assigned to the old array (pointer).



                    Vectors               112
FOR EXAMPLE, SUPPOSE WE HAVE
THE FOLLOWING, WITH n = 130:

vector<double> weights;

for (int j = 0; j < n; j++)
   weights.push_back (j + 0.1);

                     TH
AFTER THE 100 ITERATION OF THE
for LOOP, PART OF MEMORY LOOKS
LIKE THIS:
                          Vectors   113
    start
                 0.1    weights [0]
                 1.1    weights [1]
    finish




end_of_storage
                 99.1   weights [99]

                        weights[?]

                        Vectors        114
                            TH
AT THE START OF THE n
ITERATION, finish = end_of_storage, SO
A NEW ARRAY OF TWICE THE
CAPACITY IS CREATED, THE ITEMS
FROM weights ARE COPIED TO THE
NEW ARRAY, THE NEW-ARRAY
POINTER IS COPIED TO THE OLD-
ARRAY POINTER, (NAMELY, weights),
AND NEW VALUE IS APPENDED:
                  Vectors           115
    start
                 0.1   weights [0]
                 1.1   weights [1]
    finish
                 100.1 weights [100]
                 101.1 weights [101]


end_of_storage
                       weights [199]


                          Vectors      116
FOR THE push_back METHOD, WHAT
ARE THE TIME ESTIMATES?

ON AVERAGE, NO RE-SIZING IS
REQUIRED, AND THE APPENDING
TAKES ONLY CONSTANT TIME. THAT
IS, averageTime(n) IS CONSTANT.


                Vectors           117
LET n REPRESENT THE SIZE OF THE
ARRAY. IF RE-SIZING IS REQUIRED,
THEN ALL n ITEMS MUST BE COPIED
TO THE NEW ARRAY, SO worstTime(n)
IS LINEAR IN n. IN FACT, IN ANY
SEQUENCE OF n push_backS, THERE
WILL BE ONLY ONE RE-SIZING AND
COPYING.

               Vectors         118
TO INSERT AT SOMEWHERE OTHER
THAN THE BACK OF THE vector
OBJECT, THE METHOD IS

iterator insert (iterator position, const T& x);




                           Vectors                 119
THE ITEM x WILL BE INSERTED AT
LOCATION start + position, BUT FIRST,
ITEMS AT THAT LOCATION AND
HIGHER ARE MOVED TO OPEN A
SPACE AT LOCATION start + position.




                 Vectors              120
FOR EXAMPLE, SUPPOSE itr IS
POINTING TO INDEX 1 IN THE vector
OBJECT weights SHOWN EARLIER. IF
WE CALL


weights.insert (itr, 0.6);



THE RESULT WILL BE AS FOLLOWS:
                             Vectors   121
    start
                 0.1   weights [0]
                 0.6   weights [1]
                 1.1
    finish             weights [2]

                 100.1 weights [101]


end_of_storage
                       weights [199]


                         Vectors       122
AN ITERATOR POINTING TO THE
NEWLY INSERTED ITEM IS
RETURNED. THIS WILL BE
DIFFERENT FROM THE INITIAL
VALUE OF position IF RE-SIZING
OCCURS. SO, TO BE SAFE, USE THE
RETURN VALUE INSTEAD OF THE
SECOND ARGUMENT:
itr = weights.insert (itr, new_item);

                           Vectors      123
FOR AN INSERTION AT THE
BEGINNING OF THE vector OBJECT,
ALL OF THE ITEMS WILL BE MOVED,
SO worstTime(n) IS LINEAR IN n. ON
AVERAGE, ABOUT HALF OF THE
ITEMS WILL BE MOVED, SO
averageTime(n) IS ALSO LINEAR IN n.

                Vectors              124
DELETIONS ARE SOMEWHAT SIMPLER
THAN INSERTIONS BECAUSE RE-
SIZING IS NOT AN ISSUE. FOR
DELETIONS OTHER THAN AT THE
BACK, THE GAP LEFT BY THE
DELETION IS FILLED IN BY MOVING
DOWN ITEMS FROM HIGHER
LOCATIONS.
                Vectors           125
   Summary Slide 1

§- The Standard Template Library (STL) provides 10
      container classes for solving a wide range of
        problems.

§- Containers fall into one of three classifications:
   1) sequence containers
   2) adapters
   3) associative containers.



                            Vectors                     126
  Summary Slide 2
§- The array data structure is a sequence container.
  - It defines a block of consecutive data values of the
    same type.
  - Arrays are direct access containers.
      §- An index may be used to select any item in the list
         without referencing any of the other items




                              Vectors                          127
  Summary Slide 3
§- The vector sequence container provides direct
    access through an index and grows dynamically at
    the rear as needed.
    - Insertion and deletion at the rear of the sequence
      is very efficient
        §- these operations inside a vector are not efficient.




                              Vectors                        128
  Summary Slide 4
§- The list sequence container stores elements by
    position.
  - List containers do not permit direct access
    §- must start at the first position (front) and move from
       element to element until you locate the data value.
  - The power of a list container is its ability to
    efficiently add and remove items at any position in
    the sequence.




                               Vectors                          129
  Summary Slide 5
§- stacks and a queues are adapter containers that
    restrict how elements enter and leave a sequence.
  - A stack allows access at only one end of the
    sequence, called the top.
  - A queue is a container that allows access only at
    the front and rear of the sequence.
      §- Items enter at the rear and exit from the front.

§- Similar to a stack or queue, the priority queue
    adapter container restricts access operations.
      §- Elements can enter the priority queue in any order.
      §- Once in the container, only the largest element may
         be accessed.
                               Vectors                      130
  Summary Slide 6
§- A set is a collection of unique values, called keys or
    set members.
  - The set container has a series of operations that
    allow a programmer to determine if an item is a
    member of the set and to very efficiently insert and
    delete items.

§- A map is a storage structure that allows a
    programmer to use a key as an index to the data.
  - Maps do not store data by position and instead use
    key-access to data allowing a programmer to treat
    them as though they were a vector or array.

                           Vectors                   131
  Summary Slide 7
§- Vectors have several functions to allow users direct
    access to individual elements
  - Vectors allow direct assignment, pass by reference,
  and as a return type of a function

§- Vector implements an iterator to allow users to walk
  through the data.




                          Vectors                   132

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:6
posted:1/30/2012
language:English
pages:130