map中end()迭代器second值默认为1
查看原帖
map中end()迭代器second值默认为1
201897
Ancers楼主2023/1/11 11:52

做这个题用find找到对应迭代器才发现map尾部的迭代器的value值默认为1

#include <iostream>
#include <cstdio>
#include <map>
using namespace std;
map<string, int> name;
int n, m;
inline void init(){
    cin >> n;
    string s;
    for (int i(1); i <= n; ++i){
        cin >> s;
        name.insert(make_pair(s, 1));
    }
}
inline void doit(){
    cin >> m;
    string s;
    for (int i(1); i <= m; ++i){
        cin >> s;
        map<string, int>::iterator it = name.find(s);
        if (it->second == 1){
            //cout << it->second << endl;
            cout << "OK" << endl;
            it->second = 2;
        }
        else if (it->second == 2)
            cout << "REPEAT" << endl;
        else if (it == name.end()) cout << "WRONG" << endl;
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL),cout.tie(NULL);
    //freopen("in.txt", "r", stdin);
    init();
    doit();
    return 0;
}

用样例输入时输入到e时,由于map中没有e,it得到尾部迭代器,但是由于尾部迭代器->second默认为1所以输出了OK
解决办法是将it与尾部迭代器的判断放在最前面

2023/1/11 11:52
加载中...