C++ haspmap用法
#include <hash_map> #include <map> //set集合容器,实际是一棵树,每棵子树的左结点小于根节点的值, //而根节点的值小于右节点的值,整棵树可以用中序遍历得到一个 //由小到大的值——类似的容器有,multiset,map,multimap. #include<set> #include <string> #include<iostream>//如果不小心写成#include<iostream.h>就会提示:error C2679: binary '<<' : //no operator defined which takes a right-hand operand of type '' (or there is no acceptable conversion) using namespace std;//如果没有这句,下面的根本就执行不下去。会提示:error C2065: 'set' : undeclared identifier int main(void) {
//if (0 % 54 == 0) //{ // cout << "可以整除" << endl; //} //else //{
// cout << "不能整除" << endl; //} set<int> s; //set的插入由,insert() /*map<string, int> mpDatas; mpDatas.insert(pair<string, int>("ganquanfu", 28)); cout << mpDatas["ganquanfu"] << endl;*/
//pair<string, int > myPair = mpDatas.begin();
pair<set<int>::iterator,bool> p; //pair<iterator,bool>insert() //可以帮你检查是否插入成功,而且帮你提供所插入元素的迭代器位置 for(int i=0;i<5;i++) { for(int j=0;j<4;j++) { p=s.insert(i*4+j); if(p.second) { cout<<"插入新元素:"<<*(p.first)<<" "; } else { cout<<"插入失败,要插入的元素可能存在"<<endl; } } cout<<endl; } cout<<endl<<"---------------------------------------------"<<endl; //set容器的遍历 set<int>::iterator x,xend; xend=s.end(); int y=1; for(x=s.begin();x!=xend;x++) { cout<<*x<<" "; y++; if(y>5) { cout<<endl; y=1; } } cout<<endl<<"---------------------------------------------"<<endl; //set容器的删除 erase()可以删除制定位置、等于某个值、某个区间上的元素,clear()删除所有元素 for(x=s.begin();x!=s.end();) {
if((*x)%4!=0) { x = s.erase(x); } else { ++x; } } y=1; for(x=s.begin();x!=xend;x++) { cout<<*x<<" "; y++; if(y>5) { cout<<endl; y=1; } } cout<<endl<<"---------------------------------------------"<<endl; //反相迭代器 set<int>::reverse_iterator w,wend; wend=s.rend(); for(w=s.rbegin();w!=wend;w++) { cout<<*w<<endl; } cout<<endl<<"---------------------------------------------"<<endl; // // // 元素的搜索 // // find() // set<int>::iterator o; o = s.find(16); if (o == s.end()) { cout << "没有找到" << endl; } else {
cout << *o << endl; }
int wait; cin >> wait; return 0; }