擦除列表中的struct元素

时间:2016-11-10 08:54:18

标签: c++ struct

我要做的是从列表中删除一个元素。元素是结构。我很困难。在线示例不适用于struct元素。我试图将键/值设置为默认值,但是一旦我遍历数据,它就会打印一个空格,这意味着该元素仍然存在。我需要完全删除它。以下是我的代码。

.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
      }
    }
  }
}

3 个答案:

答案 0 :(得分:2)

%load_ext Cython key,但列表中包含std::string个 此外,Node是列表的最后一个元素,而不是data[i].back()

您可以使用*it删除迭代器对应的元素:

erase

现在,使用C ++ 11,以下内容应该足够了:

template<typename K, typename V, int CAP>
inline void HashTable<K, V, CAP>::deleteKey(const K & key)
{
  for (int i = 0; i < CAP; i++)
  {
    typename list<Node>::iterator it = data[i].begin();
    while (it != data[i].end())
    {
      if (it->key == key)
      {
         // Make 'it' a valid iterator to the next element
         it = data[i].erase(it);
      }
      else
      {
         // Only increment if we didn't erase
         it++;
      }
    }
  }
}

但由于这是一个哈希表,可能是template<typename K, typename V, int CAP> inline void HashTable<K, V, CAP>::deleteKey(const K & key) { for (auto& bucket: data) { bucket.remove_if([&] (auto& item) { return item->key == key; }); } } 中的索引是data的哈希,所以你可以把它变成一个单行:

key

或者,因为您只需要找到一个元素(您的键只映射到一个值),您可以获得更长但更高效的效果:

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; });
}

答案 1 :(得分:0)

使用remove()的最后一次尝试几乎是正确的解决方案。您只需使用迭代器进行删除:

   data[i].remove(it);
   break;  // found the element, iterator is invalid anyway: exit loop

这是假设&#39;键&#39;是独一无二的。

答案 2 :(得分:0)

Rene想到了擦除,它确实需要一个迭代器。 list::remove搜索整个列表以匹配给定值并删除所有匹配项。因此,请尝试data[I].erase(it)