c++ - 如何为未知容器声明迭代器变量

标签 c++ iterator containers

如何为未知的 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/

相关文章:

java - 如何在Java中使用Iterator/Iterable?

python - 我如何使用 GeneratorExit?

c++ - 环形缓冲区的有效边界检查

c++ - 扩展 vector 迭代器以满足我的需求

html - 显示:无属性在响应式网站上不工作

c++ - STL 映射到自身?

c++ - 体系结构 x86_64 的 undefined symbol :cv::CascadeClassifier::CascadeClassifier()

c++ - (如何)我可以为 Boost MultiIndex 近似 "dynamic"索引( key 提取器)吗?

c++ - 声明一个与给定模板参数的函数具有相同签名的函数

c++ - 如何使用 GDB 进入一个函数而不是它的参数