gpt4 book ai didi

c++ - 迭代器和 STL 容器

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:27:56 25 4
gpt4 key购买 nike

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

我有一些代码及其作品:

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

关于c++ - 迭代器和 STL 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16171020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com