[英]Why unordered_set<string::iterator> does not work?
I'm trying to get a list of iterators to erase from a string.我正在尝试获取要从字符串中删除的迭代器列表。 I wanted to do it with unsorted_set because access time is constant and I'll be doing lookup often but it gives me a compile error.
我想用 unsorted_set 来做,因为访问时间是恒定的,我会经常查找,但它给了我一个编译错误。
unordered_set<string::iterator> to_erase
However if i try to define vector<string::iterator> to_erase
it works. unordered_set<string::iterator> to_erase
但是,如果我尝试定义vector<string::iterator> to_erase
它可以工作。
But then when I try to do:但是当我尝试这样做时:
find(to_erase.begin(),to_erase.end(),it)
It doesn't work它不起作用
I have not checked but it looks like the string iterator does not define a hash code.我没有检查,但看起来字符串迭代器没有定义 hash 代码。 Anything stored in an unordered_* has to have a hash.
存储在 unordered_* 中的任何内容都必须具有 hash。
I am not sure how you would do it since the internal char* of the iterator is hidden from you.我不确定你会怎么做,因为迭代器的内部 char* 对你是隐藏的。
Mooing Duck contributed the following from http://coliru.stacked-crooked.com/a/a8d75d3ac153a799 Mooing Duck 从http://coliru.stacked-crooked.com/a/a8d75d3ac153a799贡献了以下内容
#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
struct str_it_hasher {
std::size_t operator()(std::string::const_iterator it) const {
return std::hash<const char*>{}(&*it);
}
};
int main() {
std::unordered_set<std::string::iterator, str_it_hasher> set;
std::string a = "apple";
set.insert(a.begin());
set.find(a.begin());
set.erase(a.begin());
}
An iterator of a string can be easily converted back and forth to index:字符串的迭代器可以轻松地来回转换为索引:
auto idx = iter - str.begin();
auto iter = idx + str.begin();
Then you can store the indices.然后你可以存储索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.