【问题标题】:Iterate through an stl container in c++?在c ++中迭代一个stl容器?
【发布时间】:2017-06-15 03:57:05
【问题描述】:

我在迭代可能具有任意数量数据结构(列表、向量等)的模板时遇到问题

对于给定的模板,是否有一种万无一失的方法来遍历它?我在声明类型时遇到了麻烦,是的,我尝试了“auto”和“auto&”,它们似乎根本不起作用。谢谢指点。

template<typename ElementType, typename ContainerType> 
ElementType findMax(ContainerType& container) {
for (typeid(container).name i = container.begin(); i !=container.end(); ++i){
    cout << i;
}
return 10;
}

【问题讨论】:

  • 你有什么问题? auto 有什么问题?什么根本不起作用?为什么需要type
  • 为什么 'auto' 不适合你?
  • 是的。 auto 直到 C++11 才被添加
  • .name 只是一个字符串!
  • 为什么不直接使用调用代码中的std::max_element 让整个函数变得毫无意义?

标签: c++ list vector stl


【解决方案1】:

让它成为自动的。

for (auto i = container.begin(); i != container.end(); ++i)

如果你不能使用 C++11,你可以在容器中使用 typedefs。

for (typename ContainerType::iterator i = container.begin(); i != container.end(); ++i)

请注意,代码并不关心ContainerType 是一个数组的情况。

另外,我认为你想打印容器的内容,而不是迭代器本身。

    cout << *i;

(live example)

【讨论】:

  • 嗯,我首先只是试图打印出任何结构,我可以返回除 int 以外的其他内容。我确实收到错误:'i' 不包含类型。 - 使用该代码
  • @LearningLaw 我编辑了,但循环没有改变。它的工作原理 - 看现场例子。
  • 感谢 IDE 正是我所需要的,我可以使用 thx @ikh
  • ContainerType::iterator 之前需要一个typename
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-16
  • 2010-10-17
  • 2011-06-22
  • 2014-12-05
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多