如何将迭代器作为 hash_map 的键?
你会如何在 gcc、Microsoft c++ 下定义它?
例如
vector<string>::iterator i;
hash_map<vector<string>::iterator, int> h;
或
list<string>::iterator i;
hash_map<list<string>::iterator, int> h;
这会产生错误,因为迭代器未预定义为字符串,而其他类型是...
Blockquote
最佳答案
在关联容器中存储 vector 的迭代器或将它们用作键不是一个好主意,因为 vector 的迭代器不稳定,也就是说,它们在 insert
上失效。 , remove
, resize
, push_back
等等(参见 Iterator invalidation rules)。
在这方面,普通索引要安全得多:
hash_map<size_t, int> h;
您可以通过简单地将索引转换为迭代器:
size_t index = ...
std::vector<std::string> vec(...);
std::vector<std::string>::iterator i = vec.begin() + index;
迭代器返回索引:
index = i - vec.begin();
关于c++ - 你如何将迭代器作为 hash_map 的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7599407/