【发布时间】:2011-09-18 06:59:33
【问题描述】:
我试图更好地掌握迭代器和泛型函数。我认为编写一个将container1 < container2 <type> > 转换为container3 <type> 的函数将是一个有用的练习。例如,它应该能够将vector< deque<int> > 转换为list<int>。
我认为所有容器访问都应该通过迭代器,就像 <algorithm> 中的函数一样。
这是我的代码:
#include <iterator>
#include <algorithm>
// COCiter == Container of Containers Iterator
// Oiter == Output Iterator
template <class COCiter, class Oiter>
void flatten (COCiter start, COCiter end, Oiter dest)
{
using namespace std;
while (start != end) {
dest = copy(start->begin(), start()->end(), dest);
++start;
}
}
但是当我尝试在下面的代码中调用它时:
int main ()
{
using namespace std;
vector< vector<string> > splitlines;
vector<string> flat;
/* some code to fill SPLITLINES with vectors of strings */
flatten(splitlines.begin(), splitlines.end(), back_inserter(flat));
}
我收到一条巨大的 C++ 模板错误消息,undefined reference to void flatten< ... pages of templates ...
我觉得我的代码写得太容易了,我必须需要更多的东西来确保内部容器中的数据类型与输出容器中的数据类型匹配。但我不知道该怎么办。
【问题讨论】:
-
请注意,堆栈没有迭代器,也没有开始/结束函数。如果您希望它与堆栈一起使用,您肯定必须对其进行特殊处理。
-
确实如此;我会换个问题。我实际上并不需要堆栈兼容性;只是可迭代的容器。
标签: c++ templates generics containers