计蒜客练习题:水果店(嵌套map)

这道题主要就是考察嵌套map的使用

这道题我一开始用的map+pair但是怎么写都不对。

之后就求助万能的百度发现网上都是用嵌套map做的。

别说我还真不知道map该怎么嵌套,以及怎么调用嵌套map。

map<string, map<string,int> > m; 定义在第二维,插入的话就跟二维数组一样(m[tm1][tm2] = tm3;)。

调用的话需要定义两个不同的iterator一个是外层的,一个是内层的。

具体看本题代码。

PS:注意输出格式!

附AC代码:

#include <iostream>
#include <cstring>
#include <map>
using namespace std;
int main()
{
    int n;
    cin >> n;
    map<string,map<string,int> >m;
    string temp1, temp2;
    while (n--)
    {
        int temp3;
        cin >> temp1 >> temp2 >> temp3;
        m[temp2][temp1] += temp3;
    }
    for (map<string, map<string, int> > ::iterator it = m.begin(); it != m.end(); it++)
    {
        cout << it->first <<endl;
        for (map<string, int> :: iterator it2 = it->second.begin(); it2 != it->second.end(); it2++)
        cout << "   |----" << it2->first << "(" << it2->second<<")"<< endl;
    }
    if (n != 0) cout <<endl;
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/Vikyanite/p/11745259.html