C++实验笔记
Posted ling_xiao007
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
以上是关于C++实验笔记的主要内容,如果未能解决你的问题,请参考以下文章