【发布时间】:2019-12-02 12:44:42
【问题描述】:
我正在尝试了解迭代器的工作原理。
我已经构建了以下代码:
list<Bucket<Key,Val>> *array;
template<typename Key, typename Val>
class Bucket
{
public:
Bucket(Key key, Val value)
{
this->key = key;
this->value = value;
}
~Bucket(){}
const Key getKey() const
{
return key;
}
const Val getValue() const
{
return value;
}
private:
Key key;
Val value;
};
在其中一个列表中插入存储桶后,我想至少执行 2 个操作: 查找和删除。
我可以使用此代码查找给定值:
int entryNum = HashFunc()(key);
for(auto i: array[entryNum % capacity])
{
if(MatchFunc(i.getKey(),key)())
{
value = i.getValue();
}
}
但我似乎无法通过添加类似的内容来删除项目 i = 数组[entryNum % 容量].erase(i); 或删除。 但如果我这样做,它会起作用:
int entryNum = HashFunc()(key);
typename list<Bucket<Key,Val>>::iterator it;
for(auto i: array[entryNum % capacity])
{
++testcounter;
if(MatchFunc(i.getKey(),key)())
{
value = i.getValue();
}
}
for (it=array[entryNum % capacity].begin(); it!= array[entryNum % capacity].end(); ++it)
{
if(testcounter!=0) --testcounter;
else
{
array[entryNum % capacity].erase(it);
return htKeyFound;
}
}
这显然不理想,我不想在同一个列表上重复两次 + 为它保留一个计数器。但我似乎无法将它们合二为一。 当我尝试访问 it.getKey() 时,它显然不起作用并出现编译错误。 关于我做错了什么有什么建议吗?
【问题讨论】:
标签: c++ linux c++11 arraylist c++14