[英]Is it possible to generalize a function that gets an STL container as parameter?
I am new to generic functions in C++. 我是C ++中泛型函数的新手。 I have a template function that prints the inside of a vector.
我有一个模板函数,可打印矢量的内部。
template<class T>
void print(vector<T> v){
for(typename vector<T>::iterator it=v.begin(); it != v.end() ; it++)
cout << *it << endl;
}
I want to write a more generic print()
to print an STL container's inside. 我想编写一个更通用的
print()
来打印STL容器的内部。 How can I proceed from this point on? 从现在开始我该如何进行?
There's already a generic algorithm that can do that, using iterators for both the input and the output: 已经有一种通用的算法可以做到这一点,对输入和输出都使用迭代器:
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, "\n"));
As such, I would proceed by using what's already there. 因此,我将继续使用已有的内容。 If you really like the syntax of
print(container_name);
如果您真的喜欢
print(container_name);
的语法print(container_name);
(which I'll admit is attractive), you could use this as the implementation, something like this: (我承认这很有吸引力),您可以将其用作实现,如下所示:
template <class Container>
void print(Container const &c) {
std::copy(std::begin(c), std::end(c),
std::ostream_iterator<typename Container::value_type>(std::cout, "\n"));
}
I'd note that (in C++11) it's often more convenient to use a range-based for
loop than std::copy
though: 我注意到(在C ++ 11中)使用基于范围的
for
循环通常比std::copy
更方便:
template <class Container>
void print(Container const &c) {
for (auto const &item : c)
std::cout << item << "\n";
}
Either of these should work for most real containers, though I'd generally prefer the latter, not only because it's simpler, but also because it's a little more generic. 尽管我通常更喜欢后者,但这两种方法都应该适用于大多数真实的容器,这不仅是因为它更简单,而且是因为它更通用。 The first requires an actual container the defines a
value_type
member, so you can't apply it to a built-in array, for one example. 首先需要一个实际的容器,该容器定义了一个
value_type
成员,因此,例如,您不能将其应用于内置数组。 You can remove that particular limitation by using std::iterator_traits<iterator>::value_type
if you want to badly enough, but the latter avoids the problem entirely (and simplifies the code quite a bit in the process). 如果您想做得足够糟糕,可以使用
std::iterator_traits<iterator>::value_type
来消除该特定限制,但是后者可以完全避免该问题(并在此过程中大大简化了代码)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.