我必须编写一个具有 const 迭代器的容器模板类,但我必须让它实际上是一个 STL 容器的迭代器,我将其称为模板参数。
template <typename T, class StoreT = std::vector<T>>
class Store {
StoreT data;
public:
StoreT::const_iterator begin() {return data.begin()}
StoreT::const_iterator end() {return data.end()}
//other stuff
};
它是这样调用的:
Store<Foo>::const_iterator it1, it2;
for (it1 = t1.begin(), it2 = t2.begin(); it1 != t1.end(); ++it1,++it2)
cout<<*it1<<*it2; //just an example
我遇到了很多错误,而且我不知道该如何让它工作。我需要在五个小时内赶到学校。任何帮助将非常感激。 出了什么问题,我应该怎么做才能让它发挥作用?
最佳答案
您还没有提供完整的错误转储,而且您发布的代码显然是摘录,所以我要指出一些可能已经处理过的事情。
确保您包含 vector 和 iostream。
#include <vector>
#include <iostream>
您在引用 vector 时显式提供了 std namespace ,但在使用 cout 时却没有。你有“使用命名空间标准”吗?使这成为可能的地方?如果没有,那么你需要
std::cout<<*it1<<*it2; //just an example
Store 尚未定义 const_iterator,因此您对 it1 和 it2 的定义无效。您需要在 Store 的公共(public)部分中使用 typedef 或 using 语句:
public:
using const_iterator = typename StoreT::const_iterator;
此外,您还缺少 typename 关键字和一些分号。
typename StoreT::const_iterator begin() {return data.begin();}
typename StoreT::const_iterator end() {return data.end();}
我可以假设 t1 和 t2 都在某处定义了吗?
关于c++ 迭代器类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50144640/