問題描述
在離開一段時間后,我將返回 C++,并試圖清除舊瓜的灰塵.
在 Java 中,Iterator 是具有以下方法的容器的接口:hasNext()
、next()
和 remove()
.hasNext()
的存在意味著它對被遍歷的容器有限制的概念.
//帶有迭代器迭代器<字符串>iter = 樹.iterator();而 (iter.hasNext()){System.out.println(iter.next());}
在 C++ 標(biāo)準(zhǔn)模板庫中,迭代器似乎表示支持 operator++
和 operator==
的數(shù)據(jù)類型或類,但沒有限制的概念 內(nèi)置,因此在進入下一個項目之前需要進行比較.在正常情況下,用戶必須通過比較兩個迭代器來檢查限制,第二個迭代器是容器端.
向量向量;向量<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 <<" ";//應(yīng)該輸出1 4 8}
這里有趣的部分是,在 C++ 中,指針是指向數(shù)組的迭代器.STL 采用現(xiàn)有的東西并圍繞它建立約定.
我還缺少什么更微妙的地方嗎?
是的,存在很大的概念差異.C++ 使用不同的迭代器類".有些用于隨機訪問(與 Java 不同),有些用于前向訪問(如 java).甚至還有一些用于寫入數(shù)據(jù)(例如,與 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.
這篇關(guān)于C ++(stl)與Java中的迭代器,有概念上的區(qū)別嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!