在Java、C#和C++中遍历集合
生活随笔
收集整理的這篇文章主要介紹了
在Java、C#和C++中遍历集合
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在Java中,常見(jiàn)的遍歷集合方式如下:
Iterator?iter?=?list.iterator();while?(iter.hasNext())?{
?Object?item?=?iter.next();
}
也可以使用for
for?(Iterator?iter?=?list.iterator();?iter.hasNext())?{???Object?item?=?iter.next();
}
JDK 1.5引入的增強(qiáng)的for語(yǔ)法
for?(Integer?item?:?list)?{
}
在C#中,遍歷集合的方式如下:
foreach?(Object?item?in?list)?{
}
其實(shí)你還可以這樣寫(xiě),不過(guò)這樣寫(xiě)的人很少而已
IEnumerator?e?=?list.GetEnumerator();while?(e.MoveNext())?
{
?Object?item?=?e.Current;
}
在C# 2.0中,foreach能夠作一定程度的編譯期類(lèi)型檢查。例如:
IList<int>?intList?=?foreach(String?item?in?intList)?{?}?//編譯出錯(cuò)
在C++標(biāo)準(zhǔn)庫(kù)中。for_each是一種算法。定義如下:
for_each(InputIterator beg, InputIterator end, UnaryProc op)
C++中,由于能夠重載運(yùn)算符(),所以有一種特殊的對(duì)象,仿函數(shù)。
class?AddValue?{
????private:
????????T?theValue;
????public:
????????AddValue(const?T&?v)?:?theValue(v)?{
????????}
????????
????????void?operator()?(T&?elem)?const?{
????????????elem?+=?theValue;
????????}
};
vector<int>?v;
INSERT_ELEMENTS(v,?1,?9);
for_each?(v.begin(),?v.end(),?AddValue<int>(10));
轉(zhuǎn)載于:https://www.cnblogs.com/jobs/archive/2004/07/23/27008.html
總結(jié)
以上是生活随笔為你收集整理的在Java、C#和C++中遍历集合的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 问dudu
- 下一篇: c# char unsigned_dll