我想要做的是从列表中删除一个元素。元素是结构。我对此感到困难。在线示例不适用于结构元素。我试图将键/值设置为默认值,但是一旦我遍历数据,它会打印出一个空格,表示元素仍然存在。我需要彻底删除它。以下是我的代码。清除列表中的结构元素
.H文件
#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;
};
这里是删除功能我想实现。
template<typename K, typename V, int CAP>
inline void HashTable<K, V, CAP>::deleteKey(const K & key)
{
typename list<Node>::iterator it; // getters need to use const_iterator
for (int i = 0; i < CAP; i++)
{
for (it = data[i].begin(); it != data[i].end(); it++)
{
if (it->key == key)
{
// these are a few things I tried, I know this is 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 from 'const std::string' to 'const HashTable<std::string,int,100>::Node &' 10HashTable
}
}
}
}
他们都给了我错误。你写的第一个代码给了我最少的错误。它说:“错误\t C2664 \t'void std :: list :: Node,std :: allocator <_Ty>> :: remove(const _Ty&)':不能将参数1从'std :: _ List_iterator ::节点>>>'to'const HashTable :: Node&'\t 10HashTable“ –
asmcriminal
@asmcriminal看起来像拼写错误的”擦除“。您可能还需要在其他编译器中为您的编译器启用C++ 11模式。 – molbdnilo
谢谢你的工作。我以为我直接复制并粘贴它。我猜不会。 – asmcriminal