c++ - Erasing a struct element within a list -
what trying remove element list. elements structs. having difficult time this. examples online not struct elements. tried set key/values default values once iterate through data prints white space meaning element still there. need remove completely. below code.
.h file
#include<list> #include<queue> using namespace std; template <typename k, typename v, int cap> class hashtable { public: hashtable(int(*)(const k&)); bool hashtable<k, v, cap>::containskey(const k& key) const; hashtable<k, v, cap>& operator=(const hashtable<k, v, cap>&); v& operator[](const k&); // setter v operator[](const k&) const; // getter queue<k> keys() const; int size() const {return siz;}; void deletekey(const k&); private: int getindex(const k& key) const; struct node{k key; v value;}; int(*hashcode)(const k&); list<node> data[cap]; int cap; int siz; };
here delete function trying implement.
template<typename k, typename v, int cap> inline void hashtable<k, v, cap>::deletekey(const k & key) { typename list<node>::iterator it; // getters need use const_iterator (int = 0; < cap; i++) { (it = data[i].begin(); != data[i].end(); it++) { if (it->key == key) { // these few things tried, know not right. data[i].back().key = k(); data[i].back().value = v(); data[i].remove(key); // error c2664 'void std::list<hashtable<std::string,int,100>::node,std::allocator<_ty>>::remove(const _ty &)': // cannot convert argument 1 'const std::string' 'const hashtable<std::string,int,100>::node &' 10hashtable } } } }
key
std::string
, list contains node
s.
also, data[i].back()
last element of list , not *it
.
you use erase
remove element iterator corresponds to:
template<typename k, typename v, int cap> inline void hashtable<k, v, cap>::deletekey(const k & key) { (int = 0; < cap; i++) { typename list<node>::iterator = data[i].begin(); while (it != data[i].end()) { if (it->key == key) { // make 'it' valid iterator next element = data[i].erase(it); } else { // increment if didn't erase it++; } } } }
these days, c++11, following should enough:
template<typename k, typename v, int cap> inline void hashtable<k, v, cap>::deletekey(const k & key) { (auto& bucket: data) { bucket.remove_if([&] (auto& item) { return item->key == key; }); } }
but since hashtable, presumably index in data
hash of key
, turn one-liner:
template<typename k, typename v, int cap> inline void hashtable<k, v, cap>::deletekey(const k & key) { data[hashcode(key)].remove_if([&] (auto& item) { return item->key == key; }); }
or, since need find 1 element (your keys map 1 value), can longer more efficient:
template<typename k, typename v, int cap> inline void hashtable<k, v, cap>::deletekey(const k & key) { auto& bucket = data[hashcode(key)]; auto = std::find_if(bucket.begin(), bucket.end(), [&] (auto& item) { return item->key == key; }); if (it != bucket.end()) { bucket.erase(it); } }
Comments
Post a Comment