迭代器和STL容器
Iterators and STL containers
我需要创建一个特定的构造函数来获取两个迭代器:开始迭代器和结束迭代器。
我有一些代码和它的工作原理:
#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中找到。
相关文章:
- 在STL容器中使用模板类
- 检查函数返回类型是否与STL容器类型值相同
- STL算法函数在多个一维容器上的使用
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 对象 C++ 向量的 STL 容器
- C++ STL:将空容器传递给lower_bound
- 如何在不破坏现有应用程序的情况下更改 API 中 stl 容器的数据类型?
- 在 STL 容器的 STL 容器上调用 clear
- "迭代器"和"const_iterator"不是 STL 容器的必需成员?
- 删除包含包含动态对象的 STL 容器的智能指针
- C++:在子类中扩展静态 STL 容器/映射成员?
- 是否有具有外部元素分配的序列容器(在 STL 中)?
- ostream 运算符<< 为获取 STL 容器而过载,传递 std::string 会破坏它?
- 没有 STL 容器的迭代器
- 为什么某些 STL 容器(堆栈、队列、优先级队列)不支持迭代器?
- 接受任何 STL 容器的函数
- C++ STL 容器中优先级搜索的优雅方法
- 我们如何打印出C++ STL 容器的value_type?
- 关联容器(STL)中的等式求值