一) string 常用方法
1首先 string 型数据要加上这些头文件
#include<iostream>` #include<string.h> using namespace std;2 很方便的一点就是,可以直接用 +=来对string直接处理,
string str1="hello "; string str2="Li ming"; string str3=str1+str2; cout<<str3<<endl; //(输出 hello Li ming ) string s=""; //清空 s+='a';s+='b'; //同时可以对单个字符进行加减 cout<<s<<endl; //(输出 ab) cout<<s[0]<<endl; //可以 像字串数组一样 处理其中的 各个字符3 还可以直接比较 ><= 就是按照 字典序比较 ,和strcmp() 的比较方法一样
string s="an hui"; string ss="an hui a"; string sss="an huj"; if(ss>s) printf("an hujk > an hui\n"); if(sss>s) printf("an huj > an hui\n");4 提供了find
string s="012345678910"; int position = s.find("8"); // 从头开始找,返回下标 if(position!=s.npos) //找不到时候返回s.npos 很大数字 { cout<<position; // 输出 8 } else cout<<"not find";二) vector 的基本用法 基本概念 这个其实还是数组类型的,不过是大小可变的数组,且数组的类型 可以是任意的。 可以来存 图,邻接表的形式
vector<int>V; V.push_back(10); // 数据的插入 V.empty(); // 是不是空 V.size(); // 容器大小 V.pop_back() //删除最后一个元素 V[0] //容器中的第一个元素 V.begin(); //返回第一个元素的迭代 V.end(); //返回末尾元素的迭代 reverse(V.begin(),V.end()); // 翻转整个序列 for(int i=1;i<=10;i++) num.push_back(i); reverse(num.begin(),num.end()); for(int i=0;i<num.size();i++) printf("%d ",num[i]); //翻转前输出 1--10 翻转后输出 10--1三) map 的基本用法 map<string ,int >mp; 基本概念 map其实就是一个映射的函数,一个为原像,一个为像; 在一种map的作用下 可将原像 转化为其对应的像。。
1默认初始化,对于数 初始化为0,对于字符串型 初始化为“”; 2 存入map中的数据是按照 原像的字典序排列的,用迭代器迭代时候,即就是按照字典序输出 3 mp.clear(); mp[key]=value; mp.size(); 4
**map<string, map < string , int > > mp; // 定义的时候中间有空格 map< string , map < string , int > >::iterator it1; map<string,int >::iterator it2; //map 中可以将 原像 和 像都 输出出来 it2.first it2.second 且这样输出时候只能用cout for(it1=mp.begin();it1!=mp.end();it1++) { cout<<it1->first<<endl; for(it2=it1->second.begin();it2!=it1->second.end();it2++) { cout<<it2->first<<"("<<it2->second<<")"<<endl; } }**四) set 的基本用法 **set<int>num;**
set集合容器:实现了红黑树的平衡二叉检索树的数据结构,插入元素时,它会自动调整二叉树的排列,把元素放到适当的位置,以保证每个子树根节点键值大于左子树所有节点的键值,小于右子树所有节点的键值;另外,还得保证根节点左子树的高度与右子树高度相等。 平衡二叉检索树使用中序遍历算法,检索效率高于vector、deque和list等容器,另外使用中序遍历可将键值按照从小到大遍历出来。 构造set集合主要目的是为了快速检索,不可直接去修改键值。 常用操作: 1.元素插入:insert() 2.中序遍历:类似vector遍历(用迭代器) 3.反向遍历:利用反向迭代器reverse_iterator。 例: set<int> s; ...... set<int>::reverse_iterator rit; for(rit=s.rbegin();rit!=s.rend();rit++) 4.元素删除:与插入一样,可以高效的删除,并自动调整使红黑树平衡。 set<int> s; s.erase(2); //删除键值为2的元素 s.clear(); 5.元素检索:find(),若找到,返回该键值迭代器的位置,否则,返回最后一个元素后面一个位置。 set<int> s; set<int>::iterator it; it=s.find(5); //查找键值为5的元素 if(it!=s.end()) //找到 cout<<*it<<endl; else //未找到 cout<<"未找到"; 6.自定义比较函数 (1)元素不是结构体: 例: //自定义比较函数myComp,重载“()”操作符 struct myComp { bool operator()(const your_type &a,const your_type &b) [ return a.data-b.data>0; } } set<int,myComp>s; ...... set<int,myComp>::iterator it; (2)如果元素是结构体,可以直接将比较函数写在结构体内。 例: struct Info { string name; float score; //重载“<”操作符,自定义排序规则 bool operator < (const Info &a) const { //按score从大到小排列 return a.score<score; } } set<Info> s; ...... set<Info>::iterator it;5 优先队列
priority_queue<int > Q; //默认的是最大堆 top() 是最大的值 priority_queue<int , vector < int > , greater < int > > Q; //定义一个最小堆 top() 是最小值