【问题标题】:Iterators and STL containers迭代器和 STL 容器
【发布时间】:2013-04-16 18:23:30
【问题描述】:

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

我有一些代码及其工作原理:

#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 容器太多。 有一些模板方法可以解决这个问题吗?

【问题讨论】:

  • 我问的是另一种方法。解决不了我的懒惰。
  • 您希望 A 的成员 itStartitEnd 不具体 - 对吗?
  • 类似的东西,它们会被检测到(类型集,地图等)。当构造函数调用时
  • 如果你确实重载了构造函数,你会怎么做?您会为 itStart 和 itEnd 使用什么类型?
  • 您可能会发现这很有用:stackoverflow.com/q/9938/951890

标签: c++ templates stl


【解决方案1】:

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

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());

【讨论】:

  • 你的回答很好。这就是我需要的。 THX
【解决方案2】:

std::fill之类的STL的东西之一:

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){}
  ...

【讨论】:

    【解决方案3】:

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

    输入序列由一对迭代器(开始和结束)表示。

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-01-15
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      相关资源
      最近更新 更多