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

C++ set容器

时间:2017-04-30 17:23:54      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:str   自定义类   code   中序遍历   close   for   sed   遍历   family   

set就是数学上的集合,每个元素最多只出现一次 ,自定义类型也可以构造set,但必须定义小于运算符

问题:

输入一个文本 找出所有不同的单词(连续的字母序列),按字典序从小到大输出
单词不区分大小写

思路:

利用stringstream分割出每个词,利用 set集合元素已经排好序 输出

代码:

 1 #include<iostream>
 2 #include<string>
 3 #include<sstream>
 4 #include<set>//set数学上的集合,每个元素最多只出现一次 set中元素已经从小到大排好序 
 5 using namespace std;
 6 set<string>de; //string集合 
 7 int main()
 8 {
 9     string s,buf;
10     while(cin>>s){
11         //处理字符串  将非字母的变成空格 字母全变为小写 
12         for(int i=0;i<s.length();i++)
13         {
14             if(isalpha(s[i]))s[i]=tolower(s[i]);
15             else s[i]= ;  
16         }
17         stringstream ss(s);
18         while(ss>>buf)de.insert(buf); //通过空格符分隔文本 
19     }
20         
21         //利用迭代器遍历set集合输出 
22         set<string>::iterator it; //定义前向迭代器 
23         //中序遍历集合中的所有元素  
24         for(it=de.begin();it!=de.end();it++) 
25         cout<<*it<<endl;    
26         //迭代器类似于指针 
27     
28     
29 } 

注意点:

<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。

stringstream>>result;//向result中写入值

stringstream<<t;//向流中传值

简单使用:

技术分享
1     string test="123 345 yuna hhh qwe";
2     stringstream ss(test);
3     string s;
4     cout << "按照空格读取字符串:" << endl;
5     while(ss >>s)cout<<s<<endl; 
View Code

 

C++ set容器

标签:str   自定义类   code   中序遍历   close   for   sed   遍历   family   

原文地址:http://www.cnblogs.com/zlspace/p/6789645.html

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