将std容器传递给函数 [英] Pass a std container to a function
问题描述
我想出了以下内容:
template <typename T> inline void printcontainer( std::vector<T> container )
{
for( auto it = container.begin(); it != container.end(); it++ )
{
std::cout << *it << std::endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> v;
v.push_back(5);
v.push_back(4);
v.push_back(3);
printcontainer(v);
return 0;
}
(对不起, push_backs
,visual studio不接受初始化列表... ugh !!)
(Sorry for the push_backs
, visual studio doesn't accept initializer lists...ugh!!)
现在这个函数限制为 std :: vector
,我怎样才能让它传递其他容器,如 std :: list
数组等...
now this function is limited to std::vector
, how can I make it so that I can pass other containers, like std::list
arrays etc...
推荐答案
只需对容器存储的类型不要模板,而是容器本身的类型:
Simply don't template on the type stored by the container, but on the type of the container itself:
template <typename Container>
inline void printcontainer(const Container &container)
注意, const
引用以避免不必要的复制。
Note that I changed the argument to const
reference to avoid an unnecessary copy.
成员 std :: begin
和 std :: end
或使用 range based for
loop :
You can generalize your print function to C arrays by using the non-member std::begin
and std::end
or by using a range based for
loop:
template <typename Container>
inline void printcontainer(const Container &container) {
for (const auto &v : container)
std::cout << v << "\n";
}
OT注意:您可能不需要
这里。
OT remark: You probably do not need the inline
here.
这篇关于将std容器传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!