码迷,mamicode.com
首页 > 编程语言 > 详细

C++关联容器的使用实例

时间:2014-11-05 17:11:44      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:style   io   os   使用   for   sp   on   问题   bs   

#include <iostream>
#include <set>
#include <string>
#include <map>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;

class TextQuery
{
public:
	typedef vector<string>::size_type line_no;
	TextQuery(){};
	void read_file(ifstream &is)
	{
		store_file(is);
		build_map();
	}
	string text_line(line_no) const;
	set<line_no> run_query(const string &) const;

private:
	vector<string> lines;
	map< string, set<line_no> > word_map;
	void store_file(ifstream &is);
	int build_map();
};

void TextQuery::store_file(ifstream &is)
{
	string line;
	while(getline(is,line))
		lines.push_back(line);
}

int TextQuery::build_map()
{
	vector<string>::size_type i;
	string word;
	
	for(i=0; i<lines.size(); i++)
	{
		istringstream ss(text_line(i+1));
		while(ss>>word)
			word_map[word].insert(i+1);
	}
	return 0;
}

string TextQuery::text_line(line_no line) const
{
	if(line <= lines.size())
		return lines[line-1];
	else
	{
		cout<<"line number out of range"<<endl;
		return string();
	}
}

set<TextQuery::line_no> TextQuery:: run_query(const string & str) const
{
	map< string, set<line_no> >::const_iterator iter = word_map.find(str);
	if( iter != word_map.end())
	{
		return iter->second;
	}
	else
	{
		cout<<"cant find word match "<<str<<endl;
		return set<line_no>();
	}
}
int main(void)
{
	TextQuery tq;
	set<TextQuery::line_no> set;
	//这里定义一个普通set类型都会报:typename is not allowed
	//set<int> a;
	
	ofstream out;
	ifstream in;
	string str1("I love apple");
	string str2("I love banana");
	string str3("apple love me");

	out.open("temp");
	out<<str1<<endl<<str2<<endl<<str3<<endl;
	out.close();

	in.open("temp");
	if(!in)
		cout<<"error"<<endl;
	//interface 1
	tq.read_file(in);
	//interface 2
	cout<<tq.text_line(1)<<endl;
	cout<<tq.text_line(2)<<endl;
	cout<<tq.text_line(3)<<endl;
	cout<<tq.text_line(4)<<endl;
	//interface 3
	set = tq.run_query("I");
	//这里不知道为何不能定义一个set类型的迭代器进行迭代输出
	//set<TextQuery::line_no>::iterator setiter;
	//for(setiter=set.begin(); setiter!=set.end(); setiter++)
		//cout<<*setiter<<endl;
	system("pause");
	return 0;
}


这是C++primere 4上的一个例子,拿来写了一下,发现自己还真会遇到不少问题,不过写完后发现真的是对容器的操作有了更进一步的理解。

但是我的程序遇到了一个问题就是不能定义一个set容器或者迭代器在main里面,一定义就会报错,因此程序最后想通过迭代器输出set容器的结果便不了了之,通过vs调试发现set里面的内容是正确的。

        希望高手给予解答。


C++关联容器的使用实例

标签:style   io   os   使用   for   sp   on   问题   bs   

原文地址:http://blog.csdn.net/u011412619/article/details/40826041

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!