简体   繁体   English

指向特定类型的STL-Container样式和迭代器(C ++)

[英]STL-Container styles and iterators that point to a specific type (C++)

I have a container class (called Atom) that I want to store objects of type Term in. Many STL container constructors have the form Container(Iterator first, Iterator last) to initialize the container with some set of elements. 我有一个容器类(称为Atom),我想存储Term类型的对象。许多STL容器构造函数的形式为Container(Iterator first, Iterator last) ,用一组元素初始化容器。

Now, I'd like to be able to use this form for my Atom class, but I'm unsure how to untie the iterator from its container class. 现在,我希望能够将此表单用于我的Atom类,但我不确定如何从容器类中解开迭代器。 For instance, currently I have: 例如,目前我有:

class Atom {
public:
  Atom(std::string str, 
    std::vector<Term>::const_iterator start, 
    std::vector<Term>::const_iterator end);

This only allowed vector iterators. 这只允许矢量迭代器。 How can I generalize the type of iterator I take? 我如何概括我采用的迭代器类型?

Whenever you need to generalize on types, think templates: 每当您需要对类型进行概括时,请考虑模板:

class Atom {
public:
  template <typename ForwardIterator>
  Atom(std::string str, 
    ForwardIterator start, 
    ForwardIterator end);

Now just iterate over the range, whatever it may be. 现在只需迭代范围,无论它是什么。

You can declare the constructor as a template of its own. 您可以将构造函数声明为自己的模板。 Just treat start and end as iterators and if they support that interface they will work. 只需将startend视为迭代器,如果它们支持该接口,它们将起作用。 Don't worry about forcing the iterators to handle type Term . 不要担心强制迭代器处理类型Term If the copy constructor can convert it to a Term it'll work. 如果复制构造函数可以将其转换为Term那么它将起作用。

The constructor might look like: 构造函数可能如下所示:

template<typename I> Atom(std::string str, I start, I end);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM