STL Containers by pptfiles


									              STL Containers
Data structures in STL:
 1. Sequence containers ( vectors, lists, deques )
 2. Associative containers (sets, multisets, maps, multimaps)

STL containers interface

    Constructors (default, copy, etc)
    Element access
    Element insertion
    Element deletion
      Associative Containers
Each element is added and (later) accessed via an associate key.

       Sets – key is identified with data value.

       Maps – key and value are separate.

- STL implements them using a red-black tree (balanced BST, Com S 311).

- Neither container allows duplicate keys.

- multiset and multipmap allow duplicate keys.
                        adapted from Ford & Topp “Data
                        Structures with C++ using STL”.


3   Main Index
    Main Index   Contents
                    Element in a Set

    Automatic sorting of elements (red-black tree implementation)

    Overload operators == and < by comparing the key fields.

4                         Main Index
                          Main Index   Contents
Example of Basic Operations
 #include <set>

 int arr[ ] = { 8, 4, 2, 9 };
 int arrSize = sizeof(arr) / sizeof(int);
 set<int> setA, setB(arr, arr+arrSize);
 set<int>::iterator iter; // set iterator

 cout << setB.size();    // output 4

 // iterator intialized to point at the smallest element with value 2
 iter = setB.begin();

 iter++;                // position iter at next element
 cout << *iter;         // output 4

 iter = setB.end();
 cout << *iter;         // output 9 (largest element)

 setA = setB;
                  Traversing a Set
                                       emphasize the argument being an iterator
template <typename Iterator>
void writeContainer(Iterator first, Iterator last, const string& separator = “ “)
          Iterator iter = first;

            while (iter != last)
                        cout << *iter << separator;

int arr[ ] = {8, 4, 2, 9}, arrSize = sizeof(arr) / sizeof(int);
vector<int> v(arr, arrSize);
list<int> alist(arr, arr+arrSize);
set<int> aset(arr, arr+arrSize);

writeContainer(arr, arr+arrSize);     // array: 8, 4, 2, 9
writeContainer(v.begin(), v.end()); // vector: 8, 4, 2, 9
writeContainer(alist.begin(), alist.end()); // list: 8, 4, 2, 9
writeContainer(aset.begin(), aset.end()); // in ascending order 2 4 8 9
                     Set Operations
string str = “associative”;
set<char> charSet;
set<char>::iterator iter;

for (int i = 0; i < str.length(); i++)

// length of string is 11; size of set is 8
// ‘a’, ‘s’, ‘i’ are duplicates
cout << str.length() << “ “ << charSet.size();

charSet.erase(‘t’); // remove ‘t’ from the set
iter = charSet.find(‘s’); // locate ‘s’ in the set
charSet.erase(iter);      // remove ‘s’ from the set

charSet.erase(charSet.begin(), charSet.end()); // clear the set
CLASS set                           Constructors        <set>
 Create an empty set. This is the Default Constructor.
set(T *first, T *last);
 Initialize the set by using the address range [first, last).
CLASS set                           Operations          <set>
bool empty() const;
 Is the set empty?
int size() const;
  Return the number of elements in the set.

 8                     Main Index
                       Main Index      Contents
CLASS set                          Operations          <set>
int count(const T& key) const;
  Returns the number of elements with the key value.

iterator find(const T& key);
   Search for key in the set and return an iterator pointing
   at it, or end() if it is not found.

 9                    Main Index
                      Main Index     Contents
CLASS set                          Operations      <set>
void erase(iterator pos);
  Erase the item pointed to by pos.

void erase(iterator first, iterator last);
  Erase the elements in the range [first, last).

10                    Main Index
                      Main Index     Contents
CLASS set                          Operations          <set>
iterator begin();
   Return an iterator pointing at the first member in the

iterator end();
   Return an iterator pointing just past the last member in
   the set.

11                    Main Index
                      Main Index     Contents
                 A Spell Checker
A set is efficient for storing a dictionary.

         Create a dictionary.

         Input a document as strings separated by whitespace.

         Determine if each input word is in the dictionary.

          - In case not, assume it is misspelled, and ask for actions:

                  add     ignore     misspelled
         Code for Spell Checker
void spellChecker(string& filename)
           // sets storing the dictionary and the misspelled words
           set<string> dictionary, misspelledWords;

           // dictionary and document streams
           ifstream dict, doc;
           string word;
           char response;

           // open "dict.dat"
           if (!dict)
                        cerr << "Cannot open \"dict.dat\"" << endl;

           // open the document file
           if (!doc)
                       cerr << "Cannot open " << filename << endl;

// insert each word from the file "dict.dat" into the dictionary set
            dict >> word;
            if (!dict)

           // insert into the dictionary

// read the document word by word and check spelling
           doc >> word;
           if (!doc)
             // look word up in the dictionary. if not present
             // assume word is misspelled. prompt user to add or ignore word
             if (dictionary.find(word) == dictionary.end())
                         cout << word << endl;
                         cout << " 'a' (add) 'i' (ignore) 'm' (misspelled) " ;
                         cin >> response;
                         // if response is 'a' add to dictionary; otherwise add to the
                         // set of misspelled words
                         if (response == 'a')
                         else if (response == 'm')

    // display the set of misspelled words
    cout << endl << "Set of misspelled words" << endl;
    writeContainer(misspelledWords.begin(), misspelledWords.end());
    cout << endl;
        Sieve of Eratosthenes
     Find all primes between 1 and n in sqrt(n) passes.

16                    Main Index
                      Main Index   Contents
    Implementation Using a Set
void sieve(set<int>& s, int n)
            int m, i;

            // erase any previous values in s
            s.erase(s.begin(), s.end());

            // load the set with integers 2, 3, . . ., n
            for (m = 2; m < n; m++)

            // find the primes using the Sieve of Eratosthenes.
            // look at all numbers from m = 2 to m * m > n ( n <= sqrt(n))
            for (m = 2; m * m <= n; m++)
                          // check is m is still in the set; if so remove all higher
                          // multiples of m starting with j = 2*m.
                          if(s.find(m) != s.end())
                                        i = 2 * m;                             // i is successive multiples of m
                                        while (i <= n)
                                                      i += m;                  // update i to the next multiple of m
     Set-Union Operator+ (A + B):
     The set of all elements x such that x is an element in
     set A OR x is an element in set B.

     Example: A = {1, 3, 8, 9, 10} and B = {2, 3, 6, 9}.
              A + B = { 1, 2, 3, 6, 8, 9, 10}
     Set-Intersection Operator* (A * B):
     The set of all elements x such that x is an element in
     set A and x is an element in set B.

               A * B = { 3, 9}

     Set-Difference Operator- (A - B):
     The set of all elements x such that x is an element in
     set A but x is not an element in set B.

               A - B = { 1, 8, 10}

18         Main Index
           Main Index   Contents
                        Set Intersection
template <typename T>
set<T> operator* (const set<T>& lhs, const set<T>& rhs) // the two sets are already sorted.
           // constuct intersection
           set<T> setIntersection;
           // iterators that traverse the sets
           set<T>::const_iterator lhsIter = lhs.begin(), rhsIter = rhs.begin();

           // move forward as long as we have not reached the end of either set
           while (lhsIter != lhs.end() && rhsIter != rhs.end())
                        if (*lhsIter < *rhsIter)
                                      // *lhsIter is in lhs and not in rhs. move iterator forward
                        else if (*rhsIter < *lhsIter)
                                      // *rhsIter is in rhs and not in lhs. move iterator forward
                                      // the same value is in both sets. insert one value
                                      // and move the iterators forward

           return setIntersection;

To top