作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如何为未知的 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++03 中,您需要明确地从容器类型中获取迭代器类型:
typename Container::iterator it;
typename Container::const_iterator cit;
在 C++11 中,你可以只使用 auto
:
auto my_iterator = c.begin(); // iterator in this case
auto my_iterator = c.cbegin(); // const_iterator always
另请注意,正如我的@Matthieu 建议的那样,您可以在 C++11 中使用基于范围的 for 循环来简化代码:
template <class Container>
void print(const Container& c)
{
for (const auto& elem : c)
cout << c << endl;
}
关于c++ - 如何为未知容器声明迭代器变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17233837/
我是一名优秀的程序员,十分优秀!