C++實驗筆記

4 - 5. Write a function that reads words from an input stream and stores them in a vector.Use that function both to write programs that count the number of words in the input, and to count how many times each word occurred.


#pragma once
//read.h
//read the words and save it into the vector
#ifndef read_H
#define read_H


#include <vector>
#include <iostream>
#include <string>


std::istream& read(std::istream& , std::vector<std::string>& , int &);


#endif

//read.cpp
#include "read.h"

using std::string; using std::vector; using std::istream; using std::cout; using std::endl;

std::istream& read(istream& in, vector<string>& strings, int & maxlen)
{
	string word;
	cout << "input words:" << endl;
	if (!in) return in;
	in.clear();
	while (in >> word)
		strings.push_back(word);

	maxlen = 0;
	for (vector<string>::const_iterator it = strings.begin();
	it != strings.end(); it++)
	{
		string::size_type tmp; 
		tmp = (*it).size();
		if (maxlen < tmp) maxlen = tmp;
	}
	return in;
}

/*
4 - 5. Write a function that reads words from an input stream and stores
them in a vector.Use that function both to write programs that count the 
number of words in the input, and to count how many times each word occurred.
*/
//main
#include <iostream>
#include <vector>
#include <map>
#include "read.h"
using namespace std;
int main()
{
	vector<string> words;
	int maxlen;
	read(cin, words, maxlen);

	cout << "the total words is:" << words.size() << endl;
	vector<string>::const_iterator i, j, first = words.begin(), second = words.end();
	map<string, int> sMap;
	for (i = first; i != second; ++i)
	{
		string tmpi = *i;
		sMap[tmpi] = sMap[tmpi] ? sMap[tmpi] + 1 : 1;
		/*int k = 0;
		for (j = i + 1; j != second; ++j)
		{
			string tmpj = *j;
			if (tmpi == tmpj)
				++k;
		}
		cout << tmpi << string(maxlen - tmpi.size() + 1, ' ') << k << endl;
		*/
	}
	for (i = first; i != second; ++i)
	{
		string tmpi = *i;
		cout << tmpi << string(maxlen - tmpi.size() + 1, ' ') << sMap[tmpi] << endl;
	}
	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章