// anagrams.cpp : 定义控制台应用程序的入口点。
//
//此练习是学习ifstream,istream_iterator,binary_search,next_permutation
//istream_iterator这是一个迭代器,是输入流的迭代器,
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cassert>
#include <iterator>
using namespace std;
int main(int argc, char* argv[])
{
//
//接受用户输入路径,在这里需要留心的是,ifstream的使用,ifstream就是一个类,文件输入留
// ifstream ifs(strPath.c_str())就是构造了一个ifstream的实例
//
string strPath("c://hello.txt");
cout<<"请输入要查找的文件路径: "<<endl;
cin>>strPath;
ifstream ifs(strPath.c_str());
if(!ifs.is_open())
{
cout<<"不能打开文件"<<endl;
return -1;
}
//
//从文件中读出数据
//
cout<<"正在从文件中读取数据"<<endl;
typedef istream_iterator<string> string_input;
vector<string> dictionary;
copy(string_input(ifs),string_input(),back_inserter(dictionary));
cout<<"文件中包含 "<<dictionary.size()<<" 个单词"<<endl;
//
//排序
//
sort(dictionary.begin(),dictionary.end());
vector<string>::iterator iter;
for(iter = dictionary.begin(); iter != dictionary.end(); iter++)
{
cout<<*iter<<endl;
}
//
//输入目标单词并查找,其思路是: 将要查找的单词进行变换,然后再在dictionary中查找
//必须注意的是next_permutation算法的用法
//
cout<<"请输入你要查找的单词:"<<endl;
for(string_input j(cin);j != string_input(); j++)
{
string word = *j;
sort(word.begin(),word.end());
bool bIsFind = false;
do
{
if(binary_search(dictionary.begin(),dictionary.end(),word))
{
cout<<" "<<word<<endl;
bIsFind = true;
}
}while(next_permutation(word.begin(),word.end()));
if(!bIsFind)
{
cout<<"对不起,没有找到相对应的单词!"<<endl;
}
}
return 0;
}