【发布时间】:2013-06-21 11:12:19
【问题描述】:
如何为未知的 STL 容器声明一个迭代器?例如,我想编写一个函数来接收容器并使用迭代器将其全部打印出来:
template <class Container> void print(Container c) {
// how to declare iterator???????
my_iterator = c.begin();
while(my_iterator!=c.end()) {
cout << *my_iterator << endl;
my_iterator++;
}
}
【问题讨论】:
-
c++11:
auto it = c.begin(); -
这不是“未知”——知道模板类型参数和知道类型一样好:)
-
请注意,在这种特殊情况下,您应该通过
const引用传递容器,以避免进行不必要的复制。
标签: c++ iterator containers