迭代器和STL容器

Iterators and STL containers

本文关键字:容器 STL 迭代器      更新时间:2023-10-16

我需要创建一个特定的构造函数来获取两个迭代器:开始迭代器和结束迭代器。

我有一些代码和它的工作原理:

#include <iostream>
#include <vector>
using namespace std;
template<typename T>
class A
{
public:
    T a[10];
    typename std::vector<T>::iterator itStart, itEnd;
    A(typename vector<T>::iterator itStart, typename vector<T>::iterator itEnd):itStart(itStart),itEnd(itEnd){}
    void see()
    {
        int i=0;
        while(itStart != itEnd)
        {
            cout<<*itStart<<endl;
            a[i] = *itStart;
            itStart++;
            i++;
        }
    }
};
template <typename Iterator>
double Sum( Iterator begin, Iterator end );
int main()
{
    cout << "Hello world!" << endl;
    vector<int> v;
    v.push_back(1);
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);

    class A<int> a(v.begin(),v.end());
    a.see();
    return 0;
}

但是我想让构造函数参数与所有STL容器(如Set,List,Map等)和普通数组(普通指针)一起工作。我能用通用模板的方式制作吗?像这样:

template<typename T>
class A
{
public:
    iterator<T> itStart, itEnd;
    A(iterator<T> itStart, iterator<T> itEnd):itStart(itStart),itEnd(itEnd){}
    void see()
    {
        while(itStart != itEnd)
        {
            cout<<*itStart<<endl;
            itStart++;
        }
    }
};

我知道上面的代码是错误的,但我想解释我的想法。

当然我可以重载构造函数,但是我懒得这么做。STL容器太多。有什么模板方法可以解决这个问题吗?

显然你需要让迭代器类型为类的模板参数

template<class T, class Iter>
class A
{
   Iter first, last;
   A(Iter first, iter last):first(first), last(last){}
};

但是现在显式地指定模板参数

变得很不舒服
A<int, vector<int>::iterator > a;
要避免这种情况,只需创建一个工厂函数
   template<class T, class Iter>
   A<T, Iter> make_A(Iter first, iter last)
   {
       return A<T, Iter>(first, last);  
   }
现在,您可以使用 函数,而不是直接创建A的对象
   auto my_A =  make_A<int>(v.begin(), v.end());

看看STL的一个东西,比如std::fill:

template< class ForwardIt, class T >
void fill( ForwardIt first, ForwardIt last, const T& value );

我们可以得到启发:

template<typename ITR, typename T>
class A
{
  A(ITR itStart, ITR itEnd):itStart(itStart),itEnd(itEnd){}
  ...

也许你可以利用输入序列(iseq)的概念。

输入序列由一对迭代器(begin和end)表示。

当然,您需要创建所有接受iseq而不是一对迭代器的STL算法的重载。

那么你的例子可以只使用for_each(重载以接受iseq)。

示例代码可以在TC++PL 3rd edition (Stroustrup) section 18.3.1中找到。