c++ 迭代器类型

标签 c++ iterator

我必须编写一个具有 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/

相关文章:

c++ - 简单的 C++ 链表

c++ - 大 vector 和内存保护 C++

c++ - 为任意网格生成三平面 UV?

java - ArrayList Iterator 迭代失败

c++ - 我在 map 中有 9 个元素,但 begin() 和 end() 之间的距离只有 2

c++ - 从转换后的容器元素创建离散分布

c++ - 带有插槽语义的超薄C++信号/事件机制

c++ - 在这种情况下,我应该使用 lock_guard、scoped_lock 还是 unique_lock?

c# - 任何自动关闭的 Java 迭代器(如 C#)?

Java:空指针双端队列迭代器