迭代器和STL容器
问题描述:
我需要做一些特定的构造函数来获取两个迭代器:启动迭代器和结束迭代器。迭代器和STL容器
我有一些代码和它的作品:
#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容器(如集,列表,地图等),并与正常阵列(正常指针)工作。 那么我可以用通用模板的方式吗?类似的东西:
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());
+0
Ur的答案很不错。这就是我需要的。谢谢 – Aku 2013-04-23 14:40:57
答
综观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第3版(Stroustrup)第18.3.1节中找到。
我问是另一种方式来做到这一点。不解决我的懒惰。 – Aku 2013-04-23 13:53:55
你希望'A'的成员'itStart'和'itEnd'是非特定的 - 是否正确? – 2013-04-23 13:54:26
类似的东西,它们会被检测到(Type Set,Map等)。当构建器调用 – Aku 2013-04-23 13:57:35