增强了C ++中的FOR循环 [英] Enhanced FOR loops in C++
本文介绍了增强了C ++中的FOR循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从Java切换到C ++,我想知道C ++是否包含我在java中使用的增强型for循环,例如:
I am switching from Java to C++ and I was wondering whether C++ contains the enhanced for loops that I used in java, in example:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
在C ++中这是否也是快捷方式?
Is this same "shortcut" possible in C++?
推荐答案
在C ++ 11中,如果你的编译器支持它,是的。它称为基于范围的。
In C++11, if your compiler supports it, yes it is. It's called range-based for.
std::vector<int> v;
// fill vector
for (const int& i : v) { std::cout << i << "\n"; }
它适用于C风格数组和任何类型的函数 begin )
和 end()
示例:
It works for C style arrays and any type that has functions begin()
and end()
that return iterators. Example:
class test {
int* array;
size_t size;
public:
test(size_t n) : array(new int[n]), size(n)
{
for (int i = 0; i < n; i++) { array[i] = i; }
}
~test() { delete [] array; }
int* begin() { return array; }
int* end() { return array + size; }
};
int main()
{
test T(10);
for (auto& i : T) {
std::cout << i; // prints 0123456789
}
}
这篇关于增强了C ++中的FOR循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文