c++ 容器類 迭代器類例項 輸入一組字串,找出出現的次數

心鑫發表於2014-03-29
/*
 * Character12.cpp
 *
 *  Created on: 2014-3-21
 *      Author: Administrator
 */
#include <iostream>
#include <cstring>
#include <valarray>
#include <string>
#include <list>
#include <Cstring>
#include <memory>
#include <set>
#include <map>
#include <vector>
#include <sstream>
#include <algorithm>
#include <exception>

using namespace std;
void showStr(string str) {
	cout << str << " ";
}
void showmap(pair<string, int> p) {
	cout << p.first << " " << p.second;
}
char toLow(char ch) {
	return tolower(ch); //為什麼tolower不能做函式指標呢
}
string& transStr(string& str) {
	transform(str.begin(), str.end(), str.begin(), toLow);
	return str;
}
bool coutIf(string& str) {
	cout << str << " ";
	return true;
}
int main() {
	//給vector輸值
	vector<string> orginValue;
	string cinStr;
	cin >> cinStr;
	while (cinStr != "quite") {
		orginValue.push_back(cinStr);
		cin >> cinStr;
	}
	cout << "orgin value:" << endl;
	for_each(orginValue.begin(), orginValue.end(), showStr);
	//從vector中找出不同的,並把有大寫的轉成小寫的
	set<string> setStr;
	//insert_iterator<set<string> >(setStr, setStr.begin()) //匿名類 呼叫插入迭代器的構造方法
	transform(orginValue.begin(), orginValue.end(), insert_iterator<set<string> >(setStr, setStr.begin()), transStr);
	cout << endl << "set value:" << endl;
	for_each(setStr.begin(), setStr.end(), showStr);

	//統計次數
	map<string, int> result;
	set<string>::iterator sit;
	for (sit = setStr.begin(); sit != setStr.end(); sit++) {
		result[*sit] = count(orginValue.begin(), orginValue.end(), *sit);
	}
	cout << endl << "map value:" << endl;
	for_each(result.begin(), result.end(), showmap);
	return 0;

}

相關文章