首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

stl 迭代器 测试程序 ,得到一个奇怪的结果!疑惑解决办法

2012-03-20 
stl 迭代器 测试程序 ,得到一个奇怪的结果!疑惑我做了个统计文件中单词出现个数的程序,不知道为什么每次都

stl 迭代器 测试程序 ,得到一个奇怪的结果!疑惑
我做了个   统计文件中单词出现个数的程序,不知道为什么   每次都读不出文件中第二个单词,直接从第一个单词,读到第三个单词去了,后面就一切正常了,所以最后统计是总是第二个单词的数量少一,或者没有。太奇怪了,不知道为什么,请各位一块看看。

代码如下:
        #include   <map>
#include   <iterator>
#include   <string>
#include   <iostream>
#include   <fstream>
#include   <algorithm>
#include   <vector>
using   namespace   std;

map <string,int>   histogram;
/*
//方案二
void   record(const   string&   s)
{
histogram[s]++;
}
*/

//方案一,方法二
void   record(const   string&   s)
{
cout < <s < < "   ";
map <string,int> ::iterator   it;
it   =   histogram.find(s);
if(   it   !=   histogram.end())
{
it-> second++;
}
else
{
histogram.insert(make_pair(s,1));
}
}

void   main()
{
string   infile;
cout < < "Please   input   file   name " < <endl;
cin> > infile;

ifstream   is(infile.c_str());
istream_iterator <string>   ii(is),eos,ib(is);

map <string,int> ::iterator   it;

/*
//方案一
//实现一
//遍历   文件string个数次   map(此期间map是变长的)

cout < < "file   content " < <endl;
while(   ii   !=   eos   )
{
cout < <*ii < < "   ";
it   =   histogram.find(*ii);
if(   it   !=   histogram.end())
{
it-> second++;
}
else
{
histogram.insert(make_pair(*ii,1));
}
ii++;
}
cout < < "\n   file   end " < <endl;
*/


//方案一
//实现二
for_each(   ii,eos,record);
cout < <endl;

/*
//方案二
//遍历一次   文件string个数
while(   ii   !=   eos   )
{
histogram.insert(make_pair(*ii,0));
++ii;
}
遍历一次   文件string个数
for_each(ib,eos,record);

*/
it   =   histogram.begin();
while(   it   !=   histogram.end())
{
cout < <it-> first < < "     " < <it-> second < <endl;
++it;
}
}


比如:用文件   c:\d.txt   内容为  
          ni   hao   ,   ni   ren   shi   wo   ?   ni   zai   na   li   hao   ma

此时,程序结果为:
          Please   input   file   name
          c:\d.txt
          ni   ,   ni   ren   shi   wo   ?   ni   zai   na   li   hao   ma
          ,     1
          ?     1
          hao     1
          li     1
          ma     1
          na     1
          ni     3
          ren     1
          shi     1
          wo     1


          zai     1
不知道怎么回事   读不到第二个单词   hao
大家看看怎么回事

[解决办法]
istream_iterator <string> ii(is),eos,ib(is);
你怎么能同时用2个iterator指向一个ifstream呢。
去掉一个即可。

热点排行