C++STL--map和set词频统计和单词转换

来源:互联网 发布:session用法 java 编辑:程序博客网 时间:2024/05/22 11:36

set简介

set官方参考连接:http://www.cplusplus.com/reference/set/set/

1.set是按特定顺序存储的容器,元素值唯一。 

2.set中的元素是const类型的,不能被修改,但是可以执行插入(insert)和删除(erase)。 

3.set的底部实现为RB-tree. 


map简介

map官方参考连接:http://www.cplusplus.com/reference/map/map/

1.map是由key value组成的,按特定顺序排列的关联容器。 

2.map中的key为唯一的。 

3.map的底部实现为RB-tree。 


注:insert重复的key, insert函数会忽略该key;不会报错;如在C#的dictionary中add重复的key,则会报错。


下面的参考示例主要来自C++Primer(第5版)第十一章


1、使用map和set实现词频统计

// 使用map和set实现词频统计// 满足条件:(1)不分大小写;(2)去除标点符号;(3)排除特定词库// map用来词频统计,set用来排除特定词库#include<iostream>    #include<string>    #include<fstream>    #include<map>#include<set>#include<cctype>//tolower()函数和ispunct函数  #include<algorithm> //remove_if函数 using namespace std;int main(int argc, char**argv){//map的定义  map<string, size_t> word_count;fstream in("1.txt");//定义一个输入流  string word;set<string> exclude = {"a","the","to","or"};while (in >> word){string::iterator it1;//转为小写for (it1 = word.begin(); it1 != word.end(); ++it1){*it1 = tolower(*it1);} //去除标点符号 word.erase(remove_if(word.begin(), word.end(), ispunct), word.end()); //若在排除词库中,则不统计if (exclude.find(word) != exclude.end())continue;++word_count[word];}  //输出统计结果map<string, size_t>::iterator mapi;for (mapi = word_count.begin(); mapi != word_count.end(); ++mapi){cout << mapi->first << " ";cout << mapi->second << " " << endl;}return 0;}


2、使用map实现单词转换

// 使用map实现单词转换// map用来存储转换关系#include<iostream>#include<map>#include<string>#include<fstream>//ifstream#include<sstream>//istringstreamusing namespace std;//读入给定文件,建立起转换映射map<string, string> buildMap(ifstream &map_file)  {map<string, string> trans_map;string key;string value;while (map_file >> key&&getline(map_file, value))//检查是否有转换规则if (value.size()>1) //跳过前导空格trans_map[key] = value.substr(1);  elsethrow runtime_error("no rule for " + key);return trans_map;}const string &transform(const string &s, const map<string, string> &m){auto map_it = m.find(s);if (map_it != m.cend())return map_it->second;elsereturn s;}int main(){map<string, string> trans_map;ifstream map_file("map_file.txt");if (!map_file){throw runtime_error("file can not open");return -1;}else{trans_map = buildMap(map_file);map_file.close();}ifstream input("input.txt");if (!input){throw runtime_error("file can not open");return -1;}else{string line, word;while (getline(input, line)){//定义string输入流,每次只读入一个string  istringstream stream(line);//标记每一行第一个单词第一个单词前不用输出空格bool firstword = true;  while (stream >> word){if (firstword)firstword = false;elsecout << " ";//对应转换单词cout << transform(word, trans_map); }cout << endl;}input.close();}return 0;}


原创粉丝点击