Sy_COOH 2023-11-27 16:57 采纳率: 0%
浏览 23

为什么map中的值每次都是false?!


#include<iostream>
#include<vector>
#include<unordered_map>
#define debug
using namespace std;
int find(vector<int> documents){
    unordered_map<int,bool> map;
        for (auto i:documents){
            if (map[i]){
                return i;
            }
            map.insert(pair(i,true));
      //
        }
        return -1;
}
int main(){
    #ifdef debug
    vector<int> documents = {2, 5, 3, 0, 5, 0};
    cout << find(documents) << endl;
    #endif
    // unordered_map<int,bool> map;
    // map.insert(pair<int,bool>(3,true));
    system("pause");
}
  • 写回答

2条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-11-27 18:42
    关注

    【以下回答由 GPT 生成】

    首先,你的问题出在插入元素和访问元素的逻辑上。在unordered_map中,插入元素应该使用insert函数,而访问元素应该使用find函数。
    
    下面是你的代码的修正版:
    
    ```cpp
    int find(vector<int> documents){
        unordered_map<int,bool> map;
        for (auto i:documents){
            if (map.find(i) != map.end() && map[i]){
                return i;
            }
            map[i] = true;
        }
        return -1;
    }
    

    这段代码中,我们使用了map.find(i) != map.end()来判断某个元素是否在map中存储,同时使用map[i] = true来插入元素。

    这样修改之后,应该能够解决你遇到的问题。 ```



    【相关推荐】



    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 创建了问题 11月27日