QT中foreach的使用

在标准C++中,并无foreach关键字。express

可是在QT中,能够使用这一个关键字,其主要缘由是QT本身增长了这一个关键字,就像slots和signals、emit等同样。增长的foreach关键字在编译时会进行预处理。spa

其用法为:code

foreach (varItem , Items)  // foreach(variable ,container)

其中,varItem(variable)是容器Items(container)中的一个项,至关于:variable=container.item 。遍历会从头遍历到尾。blog

如如下代码:it

QStringList slt = {"abc", "qwe", "upo"};
foreach(QString s , slt )
{
    cout<<s<<endl;
}
// 输出结果为:
abc
qwe
upo

在C#、Java等语言中,能够直接使用foreach,为语言自带关键字,用法类似。io

其中,在C++11标准中,提供了一种新的语句:范围for (range for) 语句。和这里的foreach用法相似。只是这里使用的是 “:” 而不是 “,” 。编译

其语法形式为:class

for (declaration : expression)

使用时代码以下:(参照foreach代码)容器

QStringList slt = {"abc", "qwe", "upo"};
for(QString s : slt )
{
    cout<<s<<endl;
}
// 输出结果为:
abc
qwe
upo
相关文章
相关标签/搜索