c++ - 你如何将迭代器作为 hash_map 的键?

标签 c++ visual-studio-2010 gcc

如何将迭代器作为 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/

相关文章:

CPP 文件中的 C++11 模板定义, undefined reference

c++ - Visual C++ 对 std::map 的实现

c++ - 如何在 C++ 中使用 C 空括号函数?

c++ - 为什么模板参数包必须在最后?

c++ - 使用 C++ 进行异或加密

c++ - 模板类特化的C++内联或非内联声明

visual-studio-2010 - 如何确定与 TFS 2010 中的源分支关联的工作项?

visual-studio-2010 - NUnit 2.5.7 需要在 VS2010 下显式调试附加

c# - XAML 更改 Togglebutton 内的图像源

有点与 boolean 值的比较