STL之函数对象事例

/*
 for_each()、transform、bind1st()函数的使用。
 知识点:
 如果STL函数需要一个一元函数,而现有一个能完成相应工作的自适应二元函数,则
 可以使用bind1st()或bind2nd使该二元函数适用于一元接口。

 程序输出:
 gr8:    36 39 42 45 48
 m8:     25 27 29 31 33
 sum:    61 66 71 76 81
 prod:   90 97.5 105 112.5 120
 */
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>

using namespace std;

void Show(double);
const int LIM = 5;

int main()
{
 double arr1[LIM] = {36, 39, 42, 45, 48};
 double arr2[LIM] = {25, 27, 29, 31, 33};
 vector<double> gr8(arr1, arr1 + LIM);
 vector<double> m8(arr2, arr2 + LIM);

 cout << "gr8: \t";
 for_each(gr8.begin(), gr8.end(), Show);
 cout << endl;

 cout << "m8: \t";
 for_each(m8.begin(), m8.end(), Show);
 cout << endl;

 vector<double> sum(LIM);
 transform(gr8.begin(), gr8.end(), m8.begin(), sum.begin(), plus<double>());
 cout << "sum: \t";
 for_each(sum.begin(), sum.end(), Show);
 cout << endl;

 vector<double> prod(LIM);
 transform(gr8.begin(), gr8.end(), prod.begin(), bind1st(multiplies<double>(), 2.5));
 cout << "prod: \t";
 
 for_each(prod.begin(), prod.end(), Show);
 cout << endl;

 getchar();
 return 0;
}

void Show(double d)
{
 cout << d << ' ';
}

 

/*
 程序输出:
 Enter words (enter quit to quit):
 LIU
 YAN
 MIN
 liu
 quit
 You entered the following words:
 LIU YAN MIN liu

 Alphabetic list of words:
 liu min yan

 Word frequency :
 liu: 2
 min: 1
 yan: 1
 */
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <iterator>
#include <algorithm>
#include <cctype>

using namespace std;

char toLower(char ch)
{
 return tolower(ch);
}
string &ToLower(string &st);
void display(const string &s);

int main()
{
 vector<string> words;
 cout << "Enter words (enter quit to quit): \n";
 string input;
 while(cin >> input && input != "quit")
  words.push_back(input);

 cout << "You entered the following words: \n";
 for_each(words.begin(), words.end(), display);
 cout << endl;

 //place words in set, converting to lowercase
 set<string> wordset;
 transform(words.begin(), words.end(), insert_iterator<set<string>> (wordset, wordset.begin()), ToLower);
 cout << "\nAlphabetic list of words: \n";
 for_each(wordset.begin(), wordset.end(), display);
 cout << endl;

 //place word and frequency in map
 map<string, int > wordmap;
 set<string>::iterator si;
 for (si = wordset.begin(); si != wordset.end(); si++)
  wordmap[*si] = count (words.begin(), words.end(), *si);

 //display map contents
 cout << "\nWord frequency :\n";
 for (si = wordset.begin(); si != wordset.end(); si++)
 {
  cout << *si << ": " << wordmap[*si] << endl;
 }

 getchar();
 getchar();
 return 0;
}

string &ToLower(string &st)
{
 transform(st.begin(), st.end(), st.begin(), toLower);
 return st;
}

void display(const string & s)
{
 cout << s << ' ';
}

 

 

你可能感兴趣的:(STL之函数对象事例)