istream_iterator

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值