How can I use hash_map


  • 0

    I want to use hash_map, and it works for me at my local machine. But when I submit the code, I was enrolled with a CE, saying that "Line 7: ‘hash_map’ was not declared in this scope"
    Attached is my code.

        #include <hash_map>
    
        class Solution {
        public:
            vector<int> twoSum(vector<int> &numbers, int target) {
            vector<int> result;
            hash_map<int, int> first_map;
    		for(int i =0;i <numbers.size(); i++)
            {
                if( first_map[target-numbers[i]])
    			{
    				result.push_back( first_map[target-numbers[i]]);
    				result.push_back(i+1);
    			}
    
    			first_map[numbers[i]] = i+1;
            }
    		return result;
        }
    };

  • 2
    R

    That's how to use hash_map in c++;

    Edited: Use std::unordered_map.count() should be better.

       class Solution {
        public:
            vector<int> twoSum(vector<int> &numbers, int target) {
            vector<int> result;
            unordered_map<int, int> first_map;
            for(int i =0;i <numbers.size(); i++)
            {
                if( first_map.count(target-numbers[i]))
                {
                    result.push_back( first_map[target-numbers[i]]+1);
                    result.push_back(i+1);
                }
    
                first_map[numbers[i]] = i;
            }
            return result;
        }
    };

  • 0
    H

    I doubt the solution can handle duplicate elements?
    For example, (3,2,7,5,3), target is 6.


  • 0
    J

    need help!

    if( first_map.count(target-numbers[i]))
    {
    result.push_back( first_map[target-numbers[i]]+1);
    result.push_back(i+1);
    }
    Here you haven't give values to first_map; how can the computer know where to do the retrieval?
    What is stored in first_map?


  • 0
    R

    If no values were assigned to a key in the map, the return will be ZERO in C++. One thing worthy knowing is that other languages(JAVA) will throw exception at this condition.


  • 0
    J

    Thanks for your answer!
    I was confused because I skipped this:
    first_map[numbers[i]] = i;


  • 0
    S

    when find the result, you'd better return or break from the loop.


  • 0
    Y

    Every time when you transplant your codes from local machine to your OG submit panel, you should use micro to work around different machines like this:

    
    #if defined __GNUC__ || defined __APPLE__
    #include <ext/hash_map>
    using __gnu_cxx::hash_map;
    using __gnu_cxx::pair;
    #else
    #include <hash_map>
    using stdext::hash_map
    using stdext::pair;
    #endif
    
    

    One should be clear that <hash_map> is defined in VS based complier, and use 'stdext' namespace even though it was replaced with <unordered_map> by Microsoft. g++ compiler, instead, uses '__gnu_cxx' namespace


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.