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];
}
运行结果

Qt中的遍历方式解析
本文介绍了Qt中三种不同的遍历方式:普通for循环、foreach循环以及C++11的范围for循环。通过实例展示了遍历过程中如何修改数组元素,并分析了不同遍历方式的特点。在foreach遍历中,由于值拷贝,无法直接修改原数组;而C++11的范围for循环则能通过引用修改原数组元素。
1073

被折叠的 条评论
为什么被折叠?



