《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;
}

运行部分截图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值