Home > other >  Bug in vector of list
Bug in vector of list

Time:04-21

I am designing my HashSet in c . I took vector of lists to hash the keys.

class MyHashSet {
public:
    vector<list<int>>val;
    MyHashSet() {
        val.resize(10000);
    }
    
    void add(int key) {
        
        val[key000].push_back(key);
    }
    
    void remove(int key) {
        auto lst=val[key000];
        
        for(auto i=lst.begin();i!=lst.end();i  )
          if(*i==key){lst.erase(i);return;}
       
        
    }
    
    bool contains(int key) {
        auto lst=val[key000];
        
        for(auto i=lst.begin();i!=lst.end();i  ) if(*i==key)return true;
        
                return false;
        
    }
};

Doing

MyHashSet a;
a.add(2);
a.remove(2);
cout<<a.contains(2)//it returns true somehow. 

the function returns true as if 2 a was not removed. I cannot figure out what's wrong with the code.

CodePudding user response:

auto lst=val[key000]; is a copy of the list. You modify the copy, and that copy ceases to exist at the end of the function.

Aside: you don't need to manually search for the element, there is std::list::remove

void remove(int key) {
    val[key000].remove(key);        
}

CodePudding user response:

the function returns true as if 2 a was not removed.

That's because you don't remove it (at least not from the list stored at val[key000]). auto lst=val[key000]; creates a copy of the list stored at val[key000] and you remove the element from that copy.

You would need to store it as a reference auto &lst=val[key000];

  • Related