text cover

Data Abstraction and Problem Solving with C++

Walls and Mirrors

by Frank M. Carrano

Addison Wesley Logo

example577.cpp

Go to the documentation of this file.
00001 
00015 #include <algorithm>
00016 #include <vector>
00017 #include <iostream>
00018 #include <string>
00019 
00020 using namespace std;
00021 
00022 int main()
00023 {
00024    //create a vector of strings
00025    vector<string> s;
00026 
00027    //create two vector iterators
00028    vector<string>::iterator iter1;
00029    vector<string>::iterator iter2;
00030 
00031    //add some items to the vector
00032    s.push_back("juice");
00033    s.push_back("apples");
00034    s.push_back("rice");
00035    s.push_back("juice");
00036    s.push_back("bread");
00037    s.push_back("oranges");
00038    s.push_back("juice");
00039    s.push_back("milk");
00040    s.push_back("ice cream");
00041    s.push_back("carrots");
00042 
00043    //display the vector
00044    for (iter1 = s.begin(); iter1 != s.end(); iter1++)
00045       cout << *iter1 <<  endl;
00046 
00047    // sort the vector
00048    sort(s.begin(), s.end());
00049 
00050    // search item
00051    string str("juice");
00052 
00053    // perform binary search for item
00054    // display whether item was found or not (1 or 0)
00055    cout << endl << "binary search: "
00056         << binary_search(s.begin(), s.end(), str) << endl;
00057 
00058    // find range of equal items with lower and upper bounds
00059    iter1 = lower_bound(s.begin(), s.end(), str);
00060    iter2 = upper_bound(s.begin(), s.end(), str);
00061 
00062    // display occurrences of item
00063    cout << endl <<  "Finding lower and upper bounds for "
00064         << str <<": " << endl;
00065    int i = 0;
00066    for (iter1; iter1 != iter2; iter1++)
00067       ++i;
00068    cout << i << " occurrences of " << str << endl;
00069    // find range of equal items with equal_range
00070    pair<vector<string>::iterator, vector<string>::iterator> eq =
00071       equal_range(s.begin(), s.end(), str);
00072 
00073    // display occurrences of item
00074    cout << endl <<  "Finding equal_range for "
00075         << str << ": " << endl;
00076    i = 0;
00077    for (eq.first; eq.first != eq.second; eq.first++)
00078       ++i;
00079    cout << i << " occurrences of " << str << endl;
00080 
00081    return 0;
00082 }  // end main

Generated on Sun Aug 27 21:28:56 2006 for AWLogo by  doxygen 1.4.6