我试图从一个字符串中获取一个迭代器列表来清除。我想用unsorted_set来做,因为访问时间是恒定的,而且我会经常进行查找,但它给我一个编译错误。unordered_set<string::iterator> to_erase
但是如果我尝试定义 vector<string::iterator> to_erase
它的工作原理。
但是,当我尝试做,
find(to_erase.begin(),to_erase.end(),it)
它不工作
我没有检查过,但看起来字符串迭代器没有定义哈希码。任何存储在unordered_*中的东西都必须有一个哈希码。
我不知道你会怎么做,因为迭代器的内部char*对你是隐藏的。
Mooing Duck贡献了以下内容,来自 http:/coliru.stacked-crooked.comaa8d75d3ac153a799。
#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());
}
一个字符串的迭代器可以很容易地来回转换为索引。
auto idx = iter - str.begin();
auto iter = idx + str.begin();
然后你就可以存储索引。