繁体   English   中英

为什么 unordered_set<string::iterator> 不工作?</string::iterator>

[英]Why unordered_set<string::iterator> does not work?

我正在尝试获取要从字符串中删除的迭代器列表。 我想用 unsorted_set 来做,因为访问时间是恒定的,我会经常查找,但它给了我一个编译错误。 unordered_set<string::iterator> to_erase但是,如果我尝试定义vector<string::iterator> to_erase它可以工作。

但是当我尝试这样做时:

find(to_erase.begin(),to_erase.end(),it)

它不起作用

我没有检查,但看起来字符串迭代器没有定义 hash 代码。 存储在 unordered_* 中的任何内容都必须具有 hash。

我不确定你会怎么做,因为迭代器的内部 char* 对你是隐藏的。


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

字符串的迭代器可以轻松地来回转换为索引:

auto idx = iter - str.begin();
auto iter = idx + str.begin();

然后你可以存储索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM