压平容器容器的通用函数
我正在尝试更好地掌握迭代器和泛型函数。我认为编写一个转换 container1
container1
container1
container1
container1
container1
container1 < 的函数将是一个有用的练习。容器2 <类型> >
到 container3
。例如,它应该能够将 vector<双端队列
到 list
。
我认为所有容器访问都应该通过迭代器进行,就像
中的函数一样。
这是我的代码:
#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<; ... 模板页面 ...
我觉得我的代码太容易编写了,我必须需要更多的东西来确保内部容器中的数据类型与输出容器中的数据类型匹配。但我不知道该怎么办。
I am trying to get a better hold on iterators and generic functions. I thought it would be a useful exercise to write a function that converts container1 < container2 <type> >
to container3 <type>
. For example, it should be able to convert vector< deque<int> >
to list<int>
.
I figured all the container access should be through iterators, like the functions in <algorithm>
.
Here is my code:
#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;
}
}
But when I try to call it in the following code:
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));
}
I get a huge C++ template error message, undefined reference to void flatten< ... pages of templates ...
I feel like my code was too easy to write, and I must need some more stuff to ensure that the data type in the inner containers matches the data type in the output container. But I don't know what to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现了这个问题。感谢 SFINAE(替换失败不是错误),您的编译器无法找到正确的模板,因为您尝试通过键入
在
(可能是一个拼写错误)。试试这个:start
上调用operator()
start()I found the issue. Thanks to SFINAE (Substitution failure is not an error) your compiler couldn't find the correct template because you are trying to call
operator()
onstart
by typingstart()
(probably a typo). Try this:std::accumulate
可以为您做到这一点。您需要将每个内部向量的内容收集到外部向量中。std::accumulate
can do it for you. You need to gather up the contents of each of the inside vectors into the outside vector.