the Standard Template Library by 7IE61T9r

VIEWS: 2 PAGES: 24

									the Standard Template Library

    Sets, Vectors and Algorithms
                   STL
• ANSI/ISO Standard C++ includes
  extensive library of templated functions &
  classes called…the Standard Template
  Library
  • Makes use of Generic Programming
                     STL
• Must understand Iterators & Function
  Objects
  • Must understand implicit constraints
    templated function/class definitions place on
    types used to instantiate them
                            Iterators
• STL iterators essentially identical, but
  differ from iterators we used in List class
  on tiny details
List Iterator      STL iterator       Purpose
Iterator itr;      iterator itr;      Notice capitalization
x = itr.get()      x = (*itr)         Get value referred to by itr
itr.next()         ++itr -or- itr++   Move iterator itr to point to next value
!itr.equal(itr2)   itr != itr2        Check itr and itr2 for equality
            STL Containers
• Templated classes for storing objects
  • Examples: List, Stack, Queue
• All STL containers have
  • size() – how many elements in container
  • empty() – returns true if container is empty
• Classes you store in container must
  • Have valid copy constructor
  • Have valid assignment operator
                 Defaults
• Classes provided with copy constructor &
  assignment operator by default
  • Default usually good enough
• BUT remember problem with dynamically
  allocated data members?
  • Must create your own copy constructor &
    assignment operator
            Comparing Items
• Some containers sort items they hold
  • Called Associative Conatiners
• Require you to be able to compare two
  objects in collection
  • Do this with
     • overloaded operator<
     • Explicitly provided function object
                  Comparison
• Whether use operator< or function object
  must have strict weak ordering defined
• Strict Weak Order              before – function object
   • before (x, x) is false              for comparison

   • if before(x,y) & before(y,z) both return true,
     then before(x,z) must also return true
                       STL Set
• Chapter 6 discusses STL list, stack, queue
  • Essentially same as what we’ve done
• Sets are new
  • Associative container
  • Stores sets of objects
     • No duplicates
  • insert(x) – inserts element x into set
  • remove(itr) – removes element referenced by
    iterator itr
                      Example
• Write program to read strings from
  standard in
  • Until you read “end”
• Insert into an STL set
  • Must #include <set>
• Use iterator to print out unique words
  • It is iterator over set of strings
     • set<string>::iterator itr
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main() {
  // Read strings & store in a set
  cout << "Enter strings terminated with \"end\": ";
  set<string> S;
  string w;

    while(cin >> w && w != "end")
     S.insert(w);

    // Print out strings in the set
    cout << "What you entered (without duplicates) was: ";
    for(set<string>::iterator itr = S.begin(); itr != S.end(); ++itr)
      cout << (*itr) << ' ';

    cout << endl;
    return 0;
}
                    Set Criteria
• Needs ordering criterion to determine whether it
  has duplicates or not (keeps elements in sorted
  using criterion)
• By default operator< used
   • Elements a & b are equal if a < b & b < a are both
     false
• If need different ordering criterion -example:
  ignore capitalization- must provide function
  object that does comparison
   • Function object passed to set constructor
   • Type of function object given when instantiating set
      • set<string,CompAlphabetical> instead of set<string>
                                                                #include <string>
                                                                using namespace std;
                                                                class CompAlphabetical {
                                                                  void makelower(string &s) {
                                                                    for(int i = 0; i < s.length(); i++)
                                                                      if ('A' <= s[i] && s[i] <= 'Z')
#include <iostream>                                                     s[i] = s[i] - 'A' + 'a';
#include <string>                                                  }
#include <set>                                                    public:
using namespace std;                                                bool operator()(string a, string b){
int main() {                                                          makelower(a);
  // Read strings & store in a set                                    makelower(b);
  cout << "Enter strings terminated with \"end\": ";                  return a < b;
  CompAlphabetical Cmp;                                             }
  set<string, CompAlphabetical> S(Cmp);                         };
  string w;
  while(cin >> w && w != "end")
    S.insert(w);
  // Print out strings in the set
  cout << "What you entered (without duplicates) was: ";
  for(set<string, CompAlphabetical>::iterator itr = S.begin(); itr != S.end(); ++itr)
    cout << (*itr) << ' ';

    cout << endl;
    return 0;
}
                      STL Vector
• Vector (pretty much)== array without worries
  • new/delete taken care of
  • Remembers size
      • size() comes standard
  • Can use pass by value
  • push_back(x) allows adding to end of vector
    without having to worry about exceeding
    bounds

    Must #include <vector>
                       Vector Use
vector<Point> A;
Point p;
for(int i = 0; i < 10; i++) {
   cin >> p;
   A.push_back(p);
}
cout << "read " << A.size() << " elements!" << endl;
              Vector With Size
• Don’t have to worry about vector size
• Can create vector with certain size
    vector<Point> vect(10);
• Access its elements like an array
    vector<Point> A(10);
    for(int i = 0; i < 10; i++)
     cin >> A[i];

    Can use index either way!
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;                         Reads in arbitrary number of doubles then
int main() {                                 Prints out average & standard deviation
  // Read doubles into vector V
  vector<double> V;
  double x;
  while(cin >> x)
    V.push_back(x);
  // Compute the average
  double sum = 0;
  for(int i = 0; i < V.size(); i++)
    sum += V[i];
  double ave = sum/V.size();
  // Compute standard deviation
  sum = 0;
  for(int i = 0; i < V.size(); i++)
    sum += (V[i] - ave)*(V[i] - ave);
  double stdev = sqrt(sum/(V.size() - 1));
  // Print results
  cout << "average = " << ave << endl << "stddev = " << stdev << endl;
  return 0;
}
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;                                   Don’t need to use indices.
int main() {                                           Can use iterators!
  // Read doubles into vector V
  vector<double> V;
  double x;
  while(cin >> x)
    V.push_back(x);
  // Compute the average
  double sum = 0;
  for(vector<double>::iterator p = V.begin(); p != V.end(); ++p)
    sum += (*p);
  double ave = sum/V.size();
  // Compute standard deviation
  sum = 0;
  for(vector<double>::iterator p = V.begin(); p != V.end(); ++p)
    sum += ((*p) - ave)*((*p) - ave);
  double stdev = sqrt(sum/(V.size() - 1));
  // Print results
  cout << "average = " << ave << endl << "stddev = " << stdev << endl;
  return 0;
}
           STL Algorithms
• STL also includes templated functions
• Most written with iterators so can be used
  with all STL containers
• Must #include <algorithm> to use
      STL Algorithm Example
• Sort
  • Can be used with any container that has
    random access iterators
     • Vectors, arrays
  • Takes 2 or 3 arguments
     • First element of range to sort
     • Position immediately after range last element in
       range to sort
     • (Optional) Function object to be used in place of
       operators< for comparison
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
  // Read doubles into vector V
  vector<double> V;
  double x;
  while(cin >> x)
    V.push_back(x);
  // Sort and compute median
  sort(V.begin(),V.end());
  double median;
  if (V.size() % 2 == 1)
    median = V[V.size()/2];
  else
    median = (V[V.size()/2 - 1] + V[V.size()/2])/2;
  // Print results
  cout << "median = " << median << endl;
  return 0;
}
                   But …
• What if we want to sort the numbers
  another way?
• By default uses operator<
• We want to sort another way
  • Example: largest to smallest by absolute
    value
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;

class CmpAbs {
  public:
   bool operator()(double x, double y) {
     return fabs(x) < fabs(y);
   }
};

int main() {
  vector<double> V;
  double x;
  while(cin >> x)
    V.push_back(x);
  CmpAbs C;
  sort(V.begin(),V.end(), C);
  double median;
  if (V.size() % 2 == 1)
    median = V[V.size()/2];
  else
    median = (V[V.size()/2 - 1] + V[V.size()/2])/2;
  cout << "median = " << median << endl;
  return 0;
}
Questions?

								
To top