关于->还是.的问题
以下是在C++Primer3上的一个程序的基础上改的:
#include<iostream>
#include<string>
#include<vector>
#include<fstream>
using namespace std;
vector<string>* retrieve_text()
{
string file_name;
cout<<"please enter file name:";
cin>>file_name;
ifstream infile(file_name.c_str(),ios::in);
if(! infile)
{
cerr<<"oops!unable to open file"<<file_name<<"--bailing out!"<<endl;
exit(-1);
}
else cout<<endl;
vector<string> *lines_of_text=new vector<string>;
string textline;
typedef pair<string::size_type,int> stats;
//存储最长行的行数和长度。
stats maxline;
int linenum=0;
while(getline(infile,textline,'\n'))
{
cout<<"line read:"<<textline<<endl;
if(maxline.first<textline.size())
{
maxline.first=textline.size();
maxline.second=linenum;
}
lines_of_text->push_back(textline);
linenum++;
}
cout<<"maximum lengh:"<<maxline.first<<endl;
cout<<"the number of the maximum_length line:"<<maxline.second<<endl;
cout<<"number of lines:"<<linenum<<endl;
return lines_of_text;
}
typedef pair<short,short>location;
typedef vector<location>loc;
typedef vector<string>text;
typedef pair<text*,loc*>text_loc;
text_loc* separate_words(const vector<string> *text_file)
{
vector<string> *words=new vector<string>;
vector<location> *locations=new vector<location>;
short line_pos=0;
for(;line_pos<text_file->size();++line_pos)
{
//textline:待处理的当前文本行
//word_pos:文本行中的当前列位置
short word_pos=0;
string textline=(*text_file)[line_pos];
string::size_type pos=0,prev_pos=0;
while((pos=textline.find_first_of(' ',pos))!=string::npos)
{
words->push_back(textline.substr(prev_pos,pos-prev_pos));
//将行/列信息存贮为pair
locations->push_back(make_pair(line_pos,word_pos));
++word_pos;prev_pos=++pos;
}
//处理最后一个单词
words->push_back(textline.substr(prev_pos,pos-prev_pos));
locations->push_back(make_pair(line_pos,word_pos));
}
return new text_loc(words,locations);
}
int main()
{
vector<string> *lines_of_text=new vector<string>;
lines_of_text=retrieve_text();
vector<string>::iterator iter=lines_of_text->begin();
vector<string>::iterator iter_end=lines_of_text->end();
for(;iter!=iter_end;iter++)
cout<<*iter<<endl;
text_loc *text=new text_loc;
text=separate_words(lines_of_text);
iter=text->first->begin();
iter_end=text->first->end();
vector<location>::iterator iter1=text->second->begin();
for(;iter!=iter_end;iter++,iter1++)
{
cout<<*iter<<":"<<(*iter1).first<<","<<(*iter1).second<<endl;//为什么这里是用.,在text_loc中的loc*不是个指针吗,像text->second一样不应该
} //用->吗?(这里换成->程序会报错)
}