为什么C++std容器迭代器会忽略其底层容器的一些模板参数



下面是一个具体的例子。在下面的代码中,我预计会出现类似";无法分配std::map<类型的值int,int,cmp>:std::map<类型的变量的迭代器int,int>:迭代器";。然而,我能够在没有任何问题的情况下编译代码(g++C++20Wall(。谢谢你的帮助。

#include <map>
struct cmp {
bool operator()(const int a, const int b) const { return a > b; }
};
int main(int argc, char *argv[]) {
std::map<int, int> m1;
std::map<int, int>::iterator m1_it = m1.begin();
std::map<int, int, cmp> m2;
std::map<int, int, cmp>::iterator m2_it = m2.begin();
// Why do these work?
m1_it = m2.begin();
m2_it = m1.begin();
return 0;
}

Standard对迭代器类型设置了一些约束,只是强加了一些行为。

特别是:

  • 它们不必在namespace std中。因此T*可能是std::vector<T>的有效迭代器。

  • 它们不必具有与容器相同的模板参数。对于上面的例子,T*可以是任何Allocatorstd::vector<T, Allocator>的迭代器。

然而,事实上,它的类型安全性较低,模板参数较少,允许较少的实例化(编译更快,生成的类似代码较少,…(。

请注意,您的代码可能不会为编译器/库编译,因为这些编译器/库使用了迭代器的所有模板参数。

一个实际的原因是,这可能会导致可执行文件变小。您的两个映射类型可以共享一个迭代器类型,因此所有迭代器函数也是共享的。

最新更新