您的位置:首页 > 其它

使用泛型算法的例子, 使用了函数对象

2009-09-16 01:16 639 查看
Test.txt中包含以下单词:
wo shi and if chen or xuefeng, how are you?
wo or shi but chen but Xue but if and

test.cpp
// Patterns.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "vector"
#include "algorithm"
#include "iterator"
#include "string"
#include "fstream"
using namespace std;

// 小于的函数对象
class LessThan
{
public:
bool operator()(const string& s1, const string& s2)
{
return s1.size() < s2.size();
}
};

// 负责输出的函数对象
class PrintItem
{
public:
PrintItem(int lineLen = 8): m_cnt(0){}
void operator()(const string& elem)
{
m_cnt++;
cout << "Elem[" << m_cnt << "]:";
cout << elem << endl;
}
private:
int m_cnt;
};

void Process(vector<string> &vec)
{
cout << "/nInvoke some test algorithm.../n";
// 调用sort排序
cout << "sort()/n";
sort(vec.begin(), vec.end());
cout << "after sort:/n";
for_each(vec.begin(), vec.end(), PrintItem());

// 删除重复的
cout << "/nunique and erase to remove the same elem/n";
vector<string>::iterator it;
// 返回的是需要删除的位置
it = unique(vec.begin(), vec.end());
vec.erase(it, vec.end());// 删除重复的
cout << "/nAfter making sure the unique elem in vector:/n";
for_each(vec.begin(), vec.end(), PrintItem());

// 按照长度再排一次,如果长度相同,保留现有顺序, 使用函数对象
cout << "/n stable_sort according to the length of word/n";
stable_sort(vec.begin(), vec.end(), LessThan());
for_each(vec.begin(), vec.end(), PrintItem());

// 定义需要排除的单词
static string rw[] = {"and", "if", "or", "but"};
vector<string> remove_words(rw, rw+4);

// 删除那些需要排除的词
vector<string>::iterator it2 = remove_words.begin();
for (; it2!=remove_words.end(); ++it2)
{
// 当前词在vector中的个数
int cnt = 0;
cnt = count(vec.begin(), vec.end(), *it2);

cout << cnt << " instance removed:" << (*it2) << endl;
// remove 以后,分成两部分,一部分是要保留的,另一半是要删除的,返回的就是要删除的开始位置
vec.erase(remove(vec.begin(), vec.end(), *it2), vec.end());

cout << "Current show:/n";
for_each(vec.begin(), vec.end(), PrintItem());
}
}

void main()
{
vector<string> sample;
string file1;
cout << "Input file name:/n";
cin >> file1;

// 打开文件,作为输入流
ifstream infile1(file1.c_str());

// iterator的特殊形式
istream_iterator<string> input_set1(infile1), eos;
// 把文件中的单词添加到sample vector的末尾
copy(input_set1, eos, back_inserter(sample));

// 使用函数对象输出,也可以使用函数指针,但是函数指针就不能内联了,函数对象可以
for_each(sample.begin(), sample.end(), PrintItem());
cout << "/nWord number in txt: " << sample.size() << endl;

Process(sample);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: