您的位置:首页 > 其它

STL find_if使用(exam)

2010-07-08 18:02 274 查看
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <string>
#include <iterator>
#include <iomanip>
#include <numeric>
using namespace std;
int const MAX_NUM = 100;
typedef struct _NODE
{
int id;
string str;
_NODE(int id, string str) : id(id), str(str){};

friend ostream& operator <<(ostream &os, const _NODE &node)
{
return os << "(" << setw(-3) << node.id << ", " << node.str << ")" << endl;
}
}NODE;
class boundCheck
{
public:
boundCheck(int min, int max) : m_min(min), m_max(max) {};
bool operator()(const NODE &nod)
{
return nod.str.size() >= m_min && nod.str.size() <= m_max;
}
private:
int m_min;
int m_max;
};
class bOdd{
public:
bool operator()(const NODE &nod)
{
return (nod.id) % 2;
}
};
class idLess
{
public:
bool operator()(const NODE &nod, const NODE &node)
{
return nod.id < node.id;
}
};
class dicOrder
{
public:
bool operator()(const NODE &nod, const NODE &node)
{
return (nod.str) < node.str;
}
};
class appendStr
{
public:
string& operator()(string &str, const NODE &node)
{
return str.append(node.str);
}
};

void _print(const vector<NODE>::iterator &begin, const vector<NODE>::iterator &end)
{
ostream_iterator<NODE> os(cout, "");
copy(begin, end, os);
cout << endl;
}
int main(int argc, char *argv[])
{
ifstream input("input.txt");
if(!input)
{
cerr << "Can not open file: " << input << endl;
system("PAUSE");
return -1;
}

vector<NODE> inputVec;
string eachWord;

cout << "input words are: " << endl;
while(input >> eachWord)
{
NODE temp(rand() % MAX_NUM, eachWord);
inputVec.push_back(temp);

cout << temp;
}

cout << endl;

vector<NODE> result;
vector<NODE>::iterator it = inputVec.begin();
int min = 5, max = 8;
/* find the words len >5 && len < 8*/
while((it = find_if(it, inputVec.end(), boundCheck(min, max))) != inputVec.end())
result.push_back(*it++);

vector<NODE> finalRes;
vector<NODE>::iterator ite = result.begin();
/*find the words in result gain above which has odd id*/
while((ite = find_if(ite, result.end(), bOdd())) != result.end())
finalRes.push_back(*ite++);

cout << "words len in(5, 8) and has odd id are: " << endl;
_print(finalRes.begin(), finalRes.end());

cout << "sort with id: ";
stable_sort(finalRes.begin(), finalRes.end(), idLess());
_print(finalRes.begin(), finalRes.end());

cout << "sort with string dic order: " << endl;
stable_sort(finalRes.begin(), finalRes.end(), dicOrder());
_print(finalRes.begin(), finalRes.end());

cout << "append the result to one string: " << endl;
string appendRes;
appendRes = accumulate(finalRes.begin(), finalRes.end(), string(""), appendStr());
cout << appendRes << endl;

system("PAUSE");
return EXIT_SUCCESS;
}
 

 

1.从文件中读出要操作的所有单词

2.查找出所有的长度在(5, 8)之间的单词

3.在上面的基础上找出所有的id是奇数的单词

4.对上面的结果按id排序

5.按字母序排序

6.把结果拼接起来(注意:prrdication函数的返回值和第一个参数需要和accumulate()的第三个参数的类型一致)

 

想到的一些杂乱的操作, 练习一下...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息