mardi 31 octobre 2017

C++ unordered_map indexing

Environment : LeetCode C++ or g++ (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;

class TwoSum {
    unordered_map<int, int> record;        
public:

    /** Add the number to an internal data structure.. */
    void add(int number) {
        record[number]++;
    }

    /** Find if there exists any pair of numbers which sum is equal to the value. */
    bool find(int value) {
        for (auto it = record.begin(); it != record.end(); ++it) {
            int num = it->first;
            int count = it->second;
            if(num*2 == value && count >= 2){
                return true;
            }
            // if(num*2 != value && record.find(value - num) != record.end()){
            //     return true;
            // }
            if(num*2 != value && record[value - num,0] >= 1){
                return true;
            }
        }
        return false;
    }
};

int main(){
    TwoSum *A = new TwoSum();
    A->add(1);
    A->add(-2);
    A->add(3);
    A->add(6);
    cout<<A->find(-1)<<endl;
}

I used to check if some value exists in hashmap by record[value - num,0].

But under some testcase, the find function will break before iterating through all element and return 0. It confused me because it should only return true if there's a break.

So instead I use the find method and got accepted.

Could anyone tell me the reason why operator[] will affect the program like that?

Aucun commentaire:

Enregistrer un commentaire