C ++(stl)与Java中的迭代器,有概念上的区别吗?

时间:2023-02-25
本文介绍了C ++(stl)与Java中的迭代器,有概念上的区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在离开一段时间后,我将返回 C++,并试图清除旧瓜的灰尘.

在 Java 中,Iterator 是具有以下方法的容器的接口:hasNext()next()remove().hasNext() 的存在意味着它对被遍历的容器有限制的概念.

//带有迭代器迭代器<字符串>iter = 树.iterator();而 (iter.hasNext()){System.out.println(iter.next());}

在 C++ 标准模板库中,迭代器似乎表示支持 operator++operator== 的数据类型或类,但没有限制的概念 内置,因此在进入下一个项目之前需要进行比较.在正常情况下,用户必须通过比较两个迭代器来检查限制,第二个迭代器是容器端.

向量向量;向量<int>::iterator iter;//向向量中添加一些元素v.push_back(1);v.push_back(4);v.push_back(8);for (iter= v.begin(); iter != v.end(); iter++){cout <<*i <<" ";//应该输出1 4 8}

这里有趣的部分是,在 C++ 中,指针是指向数组的迭代器.STL 采用现有的东西并围绕它建立约定.

我还缺少什么更微妙的地方吗?

解决方案

是的,存在很大的概念差异.C++ 使用不同的迭代器类".有些用于随机访问(与 Java 不同),有些用于前向访问(如 java).甚至还有一些用于写入数据(例如,与 transform 一起使用).

请参阅 C++ 文档中的迭代器概念:

  • 输入迭代器
  • 输出迭代器
  • 前向迭代器
  • 双向迭代器
  • 随机访问迭代器

与 Java/C# 的微不足道的迭代器相比,这些迭代器更加有趣和强大.希望这些约定将使用 C++0x 的 Concepts 进行编码.p>

I'm returning to c++ after being away for a bit and trying to dust off the old melon.

In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed.

//with an Iterator
Iterator<String> iter = trees.iterator();
while (iter.hasNext()) 
{
    System.out.println(iter.next());
}

In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.

vector<int> vec;
vector<int>::iterator iter;

// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);

for (iter= v.begin(); iter != v.end(); iter++)
{
    cout << *i << " "; //Should output 1 4 8
}

The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.

It there any further subtlety to this that I am missing?

解决方案

Yes, there is a large conceptual difference. C++ utilizes different "classes" of iterators. Some are used for random access (unlike Java), some are used for forward access (like java). While even others are used for writing data (for use with, say, transform).

See the iterators concept in the C++ Documentation:

  • Input Iterator
  • Output Iterator
  • Forward Iterator
  • Bidirectional Iterator
  • Random Access Iterator

These are far more interesting and powerful compared to Java/C#'s puny iterators. Hopefully these conventions will be codified using C++0x's Concepts.

这篇关于C ++(stl)与Java中的迭代器,有概念上的区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:由 ResultSet 支持的 Java 迭代器 下一篇:是一个“无限"的迭代器设计不好?

相关文章

最新文章