3:查找数据
#include<bits/stdc++.h>
using namespace std;
int main()
{
//构造方式 int 那个位置代表的是 关键字 而 string 那个位置代表的是 键值
map<int,string>m;
// m[1]++;
// m[2]++;
// 插入数据
// 第一种方法:
cout << “*****************************” << endl;
cout << “第一种方法插入 !” << endl;
m.insert(pair<int ,string>(1,“stu1”));
m.insert(pair<int ,string>(2,“stu2”));
m.insert(pair<int ,string>(3,“stu3”));
map<int,string>::iterator t;
cout << “*****************************” << endl;
cout << “查找 !” << endl;
t = m.find(1);
if(t != m.end())
{
cout << “查找成功!” << endl;
}
else
{
cout << “查找失败!” << endl;
}
}
4:删除数据
#include<bits/stdc++.h>
using namespace std;
int main()
{
//构造方式 int 那个位置代表的是 关键字 而 string 那个位置代表的是 键值
map<int,string>m;
// m[1]++;
// m[2]++;
// 插入数据
// 第一种方法:
cout << “*****************************” << endl;
cout << “第一种方法插入 !” << endl;
m.insert(pair<int ,string>(1,“stu1”));
m.insert(pair<int ,string>(2,“stu2”));
m.insert(pair<int ,string>(3,“stu3”));
map<int,string>::iterator t;
for( t = m.begin(); t != m.end(); t++ )
{
cout << t->first << ’ ’ << t->second << endl;
}
cout << “*****************************” << endl;
cout << “删除 !” << endl;
t = m.find(2);
m.erase(t);
for( t = m.begin(); t != m.end(); t++ )
{
cout << t->first << ’ ’ << t->second << endl;
}
}
5:运行结果
=========================================================================
1.将map容器中(默认的递增顺序,改为递减的顺序(这里的顺序指的是关键值))
#include<bits/stdc++.h>
using namespace std;
int main(){
std::map<int, int, std::greater > m; //map默认的递增 ,这样改成递减的
//在创造map时,增加参数 std::greater,就变成增加
int a[5] = {5,4,3,2,1};
map<int,int>::iterator t;
for(int i = 0; i < 5; i++){
m[i] = a[i];
}
for(t = m.begin(); t != m.end(); t++){
cout << ’ ’ << t->first << ’ ’ << t->second << endl;
}
}
2:利用map容器实现一对多
/**
思路:我们想要的结果是 一对多 即一个人对应好几个课程号,
可以用到map<string,vector>
我还考虑了vectorv[2500],但是vector中不能表示成 一个字符串对应好几个数
所以选择了map
*/
#include<bits/stdc++.h>
using namespace std;
int main(){
int N,K;
map<string,vector >m; // 注意vector 后面得加上空格
map<string,vector >::iterator t;
scanf(“%d%d”,&N,&K);
for(int i = 1; i <= K; i++){
int nums,a;
// cin >> i >> nums;
scanf(“%d%d”,&a,&nums);//这里不要输入 i即便i是从1开始的
for(int j = 0; j < nums; j++){
// string str;
// cin >> str;
char ch[6];
scanf(“%s”,ch);
m[ch].push_back(a);
}
}
for(int i = 0; i < N; i++){
char name[6];
scanf(“%s”,name);
printf(“%s %d”,name,m[name].size()); //m[name].size() 输出一个人选择了多少门课程