Qt中的遍历
暂时列举下面3中情况:
vector<int> array1 {1, 2, 3, 4, 5};
qDebug()<<"for i: ";
//使用普通的for循环遍历,并修改
for(decltype (sizeof (array1)) i=0; i<array1.size(); i++) //decltype()函数是c++11中加入的用于获取变量类型的函数
{
array1[i] = 0;
}
for(decltype (sizeof (array1)) i=0; i<array1.size(); i++)
{
qDebug()<<"i: "<<i <<" value: " <<array1[i];
}
qDebug()<<"foreach: ";
//使用 foreach 遍历循环,并修改
foreach(auto v, array1)
{
v = 1; //此处并不能修改array1中的元素, v只是array1中元素的一个拷贝。
}
for(decltype (sizeof (array1)) i=0; i<array1.size(); i++)
{
qDebug()<<"i: "<<i <<" value: " <<array1[i];
}
qDebug()<<"c++ 11 for: ";
for(auto &v: array1) // 这里v 是 array1 中元素的
{
v = 2;
}
for(decltype (sizeof (array1)) i=0; i<array1.size(); i++)
{
qDebug()<<"i: "<<i <<" value: " <<array1[i];
}
运行结果