ถามกลับไปว่า เพราะอะไร ตัวอย่างที่มักจะยกกันขึ้นมา ก็คือ C++ มันไม่มี foreach นะพี่ (ผม) เฮ๊ย... มีนะ
ตอน C++11 ยังไม่ประกาศมาตรฐาน Qt ก็เคยทำ foreach มาให้ใช้
QList<int> list;
list << 1 << 2 << 3 << 4 << 5;
foreach (int i, list)
{
qDebug() << i;
}
พอ C++11 ประกาศใช้เราก็สามารถทำแบบนี้ได้
int arrayint[] = {1, 2, 3, 4, 5};
for (int i : arrayint) {
...
}
ทำแบบกำหนด boundary ของ container (cont) แบบนี้ก็ได้
for (auto it = cont.begin(); it != cont.end(); ++it)
หรือ จะแบบ reverse order ก็แบบนี้
for (auto it = cont.rbegin(); it != cont.end(); ++it)
เห็นแมะ C++11 โบราณตรงไหน :-)
ไม่มีความคิดเห็น:
แสดงความคิดเห็น