范围For 语句
程序员文章站
2022-03-16 19:14:22
...
For (declaration: expression)
Statement
Declaration:定义一个作为访问方式的变量。
Expression:指向需要操作的对象。
Statement:需要执行的操作。
for(int& i : vec) //若需要修改对象中的值则要加引用(&)
{
i++;
}
for (auto i : vec)//推荐使用auto类型说明符
{
cout << i << endl; // 输出更新后的数值
}
注:expression为一个“序列”,可进行自定义,需要对象满足一下条件:
指针或迭代器(*);
拥有能够返回迭代器的begin和end成员函数;
前缀自加操作符(++);
不等关系运算符(!=);
// a simple iterator sample.
#include <iostream>
using namespace std;
// forward-declaration to allow use in Iter
class IntVector;
class Iter
{
private:
int _pos;
const IntVector *_p_vec;
public:
Iter(const IntVector* p_vec, int pos) : _pos(pos), _p_vec(p_vec){}
// these three methods form the basis of an iterator for use with a range-based for loop
bool operator!=(const Iter& other) const
{
return _pos != other._pos;
}
// this method must be defined after the definition of IntVector since it needs to use it
int operator*() const;
const Iter& operator++()
{
++_pos;
// although not strictly necessary for a range-based for loop
// following the normal convention of returning a value from
// operator++ is a good idea.
return *this;
}
};
class IntVector
{
private:
int _data[100];
public:
IntVector(){}
int get(int col) const
{
return _data[col];
}
Iter begin() const
{
return Iter(this, 0);
}
Iter end() const
{
return Iter(this, 100);
}
void set(int index, int val)
{
_data[index] = val;
}
};
int Iter::operator*() const
{
return _p_vec->get(_pos);
}
// sample usage of the range-based for loop on IntVector
int main()
{
IntVector v;
for(int i = 0; i < 100; i++)
{
v.set(i,i);
}
for( int i : v)
{
cout << i << endl;
}
}
上一篇: Java中的快速排序