【问题标题】:How to declare an iterator variable for unknown container如何为未知容器声明迭代器变量
【发布时间】: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


【解决方案1】:

在 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++11 中,实际上还有更好的:for (auto const&amp; element: c)
  • @MatthieuM。当然,好点!我专注于对这个问题的字面解释。我将添加一些关于基于范围的循环的内容。
【解决方案2】:

去:

for (auto& var : container)
{
  cout << var << endl;
}

显示容器的每个元素(以及任何其他类型的容器,甚至是字符串或矢量或地图,...)

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 2018-12-09
    相关资源
    最近更新 更多