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. unordered_set<string::iterator> to_erase
However if i try to define vector<string::iterator> to_erase
it works.
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. Anything stored in an unordered_* has to have a hash.
I am not sure how you would do it since the internal char* of the iterator is hidden from you.
Mooing Duck contributed the following from 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.