#include<iostream>
#include<stdlib.h>
#include<string>
#include<map>
using namespace std;
typedef map<string,long long> URL_COUNT;
//map的打印
void print(URL_COUNT url_count){
for(map<string,long long>::iterator i = url_count.begin(); i!=url_count.end(); i++){
cout << i->first << " " << i->second <<endl;
}
}
void print_ele(map<string,long long>::iterator ele){
cout << ele->first << "=>" << ele->second << endl;
}
int main(){
//map的建立
URL_COUNT url_count;
//************************************************************
//map的插入
//map[key] = value
url_count["a"] = 1;
url_count["b"] = 2;
url_count["c"] = 3;
//insert(map<string,long long>::value_type(key,value))
url_count.insert(map<string,long long>::value_type("e",5));
//insert(make_pair(key,value))
url_count.insert(make_pair("f",6));
//insert(pair<string,int> p)
pair<string, int> p;
p.first = "g";
p.second = 7;
url_count.insert(p);
//不正确的插入方式
//url_count.insert("d",4);
print(url_count);
//*************************************************************
//map的查找
//count函数只返回0或者1
cout << url_count.count("e") << endl;
cout << url_count.count("s") << endl;
//find函数返回key对应的对象的迭代器
print_ele(url_count.find("f"));
//没有找到时返回Segmentation fault,慎用
//print_ele(url_count.find("s"));
//*************************************************************
//map的删除
//erase(key),有则删除返回1,无则返回0
cout << url_count.erase("f") << endl;
//erase(指向map元素的迭代器)
map<string,long long>::iterator i = url_count.find("g");
url_count.erase(i);
print(url_count);
return 0;
}
返回结果:
a 1
b 2
c 3
e 5
f 6
g 7
1
0
f=>6
1
a 1
b 2
c 3
e 5