?? 7-0-1.cpp
字號:
#include<iostream>
#include<map>
#include<string>
#include<vector>
using namespace std;
vector<string> split(const string& s)
{
vector<string> ret;
typedef string::size_type string_size;
string_size i=0;
//ivarinant: we have processed characters [original value of i, i)
while(i!=s.size())
{
//ignore leading blanks
//invariant: characters in range [original i, current i) are all spaces
while(i!=s.size()&&isspace(s[i]))
++i;
//find end of next word
string_size j=i;
//invariant: none of the characters in range [original j,current j)is a space
while(j!=s.size()&&!isspace(s[j]))
j++;
//if we found some nonwhitespace characters
if(i!=j)
{
//copy from s starting at i and taking j-i chars
ret.push_back(s.substr(i,j-i));
i=j;
}
}
return ret;
}
//find all the lines that refer to each word in the input
map<string, vector<int> >
xref(istream& in,
vector<string> find_words(const string&)=split)
{
string line;
int line_number=0;
map<string, vector<int> > ret;
//read the next line
while(getline(in, line))
{
if(line=="exit")
break;
++line_number;
//break the input line into words
vector<string> words=find_words(line);
//remember that each word occurs on the current line
for(vector<string>::const_iterator it=words.begin();
it!=words.end();++it)
ret[*it].push_back(line_number);
}
return ret;
}
int main()
{
//call xref using split by default
map<string, vector<int> > ret=xref(cin);
//write the results
for(map<string, vector<int> >::const_iterator it=ret.begin();it!=ret.end();++it)
{
//write the word
cout<<it->first<<"\toccurs on line(s): ";
//followed by one or more line numbers
vector<int>::const_iterator line_it=it->second.begin();
cout<<*line_it; //write the first line number
++line_it;
//write the rest of the line numbers, if any
while(line_it!=it->second.end())
{
cout<<", "<<*line_it;
++line_it;
}
//write a new line to separate each word from the next
cout<<endl;
}
return 0;
}
/*
cheng is a good student
and liu ling long is a good student too
exit
a occurs on line(s): 1, 2
and occurs on line(s): 2
cheng occurs on line(s): 1
good occurs on line(s): 1, 2
is occurs on line(s): 1, 2
ling occurs on line(s): 2
liu occurs on line(s): 2
long occurs on line(s): 2
student occurs on line(s): 1, 2
too occurs on line(s): 2
Press any key to continue
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -