variable in constructor not declared in this scope c++

Forgive me for I’m still a beginner in c++ The following code gives an error that the variable is not in scope,

error: 'vec' was not declared in this scope   
         vec[key] = value;

without changing how object is declared in the main function, how can I resolve this issue?

// Program to illustrate the working of
// objects and class in C++ Programming

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

// create a class
class MyHashMap {
public:
    /** Initialize your data structure here. */
    // vector<int> vec;
    MyHashMap() {
        vector<int> vec(1000000, -1);
    }
    
    /** value will always be non-negative. */
    void put(int key, int value) {
        vec[key] = value;
    }
    
    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    int get(int key) {
        return vec[key];
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        vec[key] = -1;
    }
};


int main() {
   int key,value;
   cin>>key>>value;
   MyHashMap* obj = new MyHashMap();
   obj->put(key,value);
   int param_2 = obj->get(key);
   obj->remove(key);
   return 0;
}

Answer

/** Initialize your data structure here. */
std::vector<int> vec;
MyHashMap():vec(1000000, -1)
{}

Leave a Reply

Your email address will not be published. Required fields are marked *