STL复习之 map & vector --- disney HDU 2142

时间:2023-03-09 08:47:35
STL复习之 map & vector  ---  disney HDU 2142

题目链接:

https://vjudge.net/problem/40913/origin

大致题意:

这是一道纯模拟题,不多说了。

思路:

map模拟,vector辅助

其中用了map的函数:

erase:

https://www.cnblogs.com/kex1n/archive/2011/12/06/2278505.html

上面这个博客的讲解非常透彻

大致的意思就是:

删除map内的一个节点。

比如我代码里的这句:

else if(op == "DELETE")
{
string name;
cin >> name;
it = mp.find(name);
if(it == mp.end())
{
printf("no such record\n");
}
else
{
mp.erase(it++);
printf("delete succeed\n");
}
}

这里就删除了it == mp.find(name)的节点。

要注意这里的

mp.erase(it++)
是避免出现程序无定义的行为
博客里写的很清楚。大致意思就是erase删除了这个节点,导致循环的时候会出现无节点的情况。这样it++就能跳过这个节点。 同样,我这段代码里也涉及到了map的find函数:
find函数用来定位数据出现位置,它返回的一个迭代器,。
当数据出现时,它返回数据所在位置的迭代器,
如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器!
所以我能用来判断是否存在name的。
it = mp.find(name);

关于vector我的代码用的不多,就是用作了一个string类的数组,这里主要用到了vector进行排序。

           vector<string> name;
for(it = mp.begin(); it != mp.end(); ++it)
{
if(it->second == mx)
{
name.push_back(it->first);
}
}
//printf("%d %d\n", mx, name.size());
sort(name.begin(), name.end());
cout << mx << " " << name.size() << endl;
for(int i = ; i < name.size(); ++i) cout << name[i] << endl;

关于vector的运用这个博主写的很好

https://www.cnblogs.com/aiguona/p/7228364.html

大致的使用方法就是:

vector<int> v1

v1.push_back()   //在数组的最后添加一个数据
v1.pop_back() //去掉数组的最后一个数据
v1.front()     //返回第一个元素(栈顶元素)
v1.begin() //得到数组头的指针,用迭代器接受
v1.end() //得到数组的最后一个单元+1的指针,用迭代器接受
v1.clear() // 移除容器中所有数据
v1.empty() //判断容器是否为空
v1.erase(pos) //删除pos位置的数据
v1.erase(beg,end)// 删除[beg,end)区间的数据
v1.size() //回容器中实际数据的个数
v1.insert(pos,data) //在pos处插入数据 下面是AC代码:
#include <iostream>
#include <cstdio>
#include <string.h>
#include <map>
#include <vector>
#include <algorithm> using namespace std;
map<string, double> mp;
map<string, double> ::iterator it; //声明一个map的迭代器 int main()
{
string op;
while(cin >> op && op != "QUIT") //根据题意QUIT时退出
{
if(op == "NEW") //模拟NEW
{
double x;
string name;
cin >> name >> x;
if(mp[name]) //如果有存
{
mp[name] = x;
printf("update succeed\n");
}
else
{
mp[name] = x;
printf("A new record\n");
}
} else if(op == "MAX") //模拟max
{
if(mp.size() == ) //若map为空则输出0 0
{
printf("0 0\n");
continue;
}
double mx = mp.begin()->second;
for(it = mp.begin(); it != mp.end(); ++it)
{
mx = max(mx, it->second); //运用max函数找到最大值
}
vector<string> name;
for(it = mp.begin(); it != mp.end(); ++it)
{
if(it->second == mx)
{
name.push_back(it->first); //如果
}
}
cout << mx << ' ' << name.size() << endl;
for(int i = ; i < name.size(); ++i)
{
cout << name[i] << endl;
}
} else if(op == "AVERAGE")//模拟ACERAGE的情况
{
double sum = ;
if(mp.size() == )
{
printf("0.00\n");
continue;
}
for(it = mp.begin(); it != mp.end(); ++it)
{
sum += it->second;
}
printf("%0.2lf\n", sum/mp.size());
} else if(op == "DELETE")
{
string name;
cin >> name;
it = mp.find(name);
if(it == mp.end())
{
printf("no such record\n");
}
else
{
mp.erase(it++);
printf("delete succeed\n");
}
}
}
}

如有疑问,欢迎评论指出!