http://blog.csdn.net/ly21st http://ly21st.blog.chinaunix.net
分类: C/C++
2011-11-23 14:45:46
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//typedef multimap< string,int >::iterator mulmap_iter;
class Query {
public:
typedef multimap< string,int >::iterator mulmap_iter;
void make_map(ifstream &in) ;
void query(string &str);
private:
multimap
map
};
void Query::make_map(ifstream &in)
{
string line;
int line_num=0;
while(getline(in,line)) {
line_num++;
smap.insert(make_pair(line_num,line));
string word;
set
istringstream str(line);
while(str>>word) {
int count=words.count(word);
if (!count) {
words.insert(word);
mulmap.insert(make_pair(word,line_num));
}
}
}
}
void Query::query(string &str)
{
pair< mulmap_iter,mulmap_iter >
pos=mulmap.equal_range(str);
if (pos.first==pos.second ) {
cout<
return ;
}
cout<<"元素出现的位置为"<
for(mulmap_iter iter=pos.first; iter!=pos.second; iter++)
{
cout<<"
}
}
int main()
{
ifstream in("aa.txt");
cout<<"输入要查找的元素:";
string str;
cin>>str;
Query q;
q.make_map(in);
q.query(str);
getchar();
getchar();
return 0;
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
文本查询程序版本2
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class TextQuery {
public:
typedef vector
void read_file(ifstream &is)
{store_file(is); build_map(); }
set
string text_line(line_no) const;
private:
void store_file(ifstream&);
void build_map();
vector
map< string,set
};
void TextQuery::store_file(ifstream &in)
{
string line;
while(getline(in,line)) {
lines_of_text.push_back(line);
}
}
void TextQuery::build_map()
{
for(TextQuery::line_no index=0; index != lines_of_text.size(); index++)
{
istringstream str(lines_of_text[index]);
string word;
while(str>>word)
word_map[word].insert(index);
}
}
set
{
map< string,set
if (iter!=word_map.end())
return iter->second;
else
return set
}
string TextQuery::text_line(line_no index) const
{
return lines_of_text[index];
}
void entry(ifstream &in,TextQuery &q,string &word)
{
q.read_file(in);
set
for(set
cout<<"(line:"<<*iter+1<<") "<
if (iset.size() == 0)
cout<<"元素"<
}
main()
{
TextQuery q;
ifstream in("aa.txt");
cout<<"输入查询的字符串:";
string word;
cin>>word;
entry(in,q,word);
getchar();
getchar();
return 0;
}