《CPlusPlusPrimer》第十二章二节编程源码——vocab功能的源码

用于练习泛型算法。

程序源码:

// 练习C++Primer Chapter12.2节中的泛型算法

#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

typedef vector<string> textwords;
typedef vector<string>::iterator VEC_STR_IT;

class PrintElem{
	int line_len;
	int cnt;
public:
	PrintElem(int len = 8): line_len(len), cnt(0) {}
	void operator()(const string & elem)
	{
		cnt++;
		cout << elem << " ";
		if( cnt % line_len == 0)
		{
			cout << '\n';
		}
	}
};

class LessThan
{
public:
	bool operator()(const string &str1, const string &str2)
	{
		// OK,必须用size,而非length.
		return (str1.size() < str2.size());
	}
};

class GreatThan
{
	int _len;
public:
	GreatThan(int len = 6) : _len(len) {}
	bool operator() ( const string & s)
	{
		return (s.size() > _len);
	}
};

void proccess_vocab(const vector<textwords> &vecs)
{
	vector<string> texts;
	vector<textwords>::const_iterator iter = vecs.begin();
	for( ; iter != vecs.end(); iter++ )
	{
		copy( (*iter).begin(), (*iter).end(), back_inserter( texts ));
	}
	sort( texts.begin(), texts.end() );
	for_each( texts.begin(), texts.end(), PrintElem());
	cout << "\n\n";

	// 消除相同词
	VEC_STR_IT it;
	it = unique( texts.begin(), texts.end());
	texts.erase(it, texts.end());
	for_each( texts.begin(), texts.end(), PrintElem());
	cout << "\n\n";
	
	// 根据自符串长度排序
	stable_sort( texts.begin(), texts.end(), LessThan());
	for_each( texts.begin(), texts.end(), PrintElem());
	cout << "\n\n";

	// 计算长度大于6的个数
	int cnt  = count_if( texts.begin(), texts.end(), GreatThan());
	cout << "the count which's size is great than 6 is: " << cnt << endl;

	static string rw[] = {"and", "if", "or", "but", "the"};
	vector<string> remove_words ( rw, rw + 5);
	VEC_STR_IT it2 = remove_words.begin();
	for( ; it2 != remove_words.end(); it2++ )
	{
		int cnt = count ( texts.begin(), texts.end(), *it2);
		cout << cnt << " instances removed: " << (*it2) << endl;
		
		texts.erase(
			remove(texts.begin(), texts.end(), (*it2)),
			texts.end());
	}
	cout << "\n\n";

	for_each( texts.begin(), texts.end(), PrintElem());
}

int main( char* args[], int argc)
{
	vector<textwords> sample;
	vector<string> vec1, vec2;
	const string inf1 = "chapter12_vocab_file1.txt", inf2 = "chapter12_vocab_file1.txt";
	
	using std::ifstream;
	ifstream infile1(inf1.c_str());
	ifstream infile2(inf2.c_str());
	
	istream_iterator<string> input_set1(infile1), eos;
	istream_iterator<string> input_set2(infile2);
	
	copy( input_set1, eos, back_inserter(vec1));
	copy(input_set2, eos, back_inserter(vec2));

	sample.push_back( vec1 );
	sample.push_back( vec2 );

	proccess_vocab(sample);

	return 0;
}

运行部分截图:


阅读更多
个人分类: C++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭