贪吃蛇游戏的c++版本,在startinterface.cpp文件中有如下代码:
void StartInterface::PrintText()
{
for (auto & point : textsnake)
{
if(point.GetX() >= 0)
point.Print();
}
}
for (auto & point : textsnake) 啥意思???
通过查阅资料,发现C++11标准新增的用法
基于范围的for循环(下面给出官方文档)
double prices [ 5 ] = { 4.99 , 10.99 , 6.87 , 7.99 , 8.49 } ;
for ( double x : prices )
std :: cout << x << std :: endl ;
例子:
//-------------------------------------------------------
/*首先操作文件“123.txt”,使其如下:
“满堂花醉 三千客
一剑霜寒 十四州
吹灭读书 灯
一身都是月 ” */
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int main()
{
fstream in;
in.open("123.txt",ios::in);
if(!in){
cerr<<"打开失败"<<endl;
return -1;
}
string line;//文本内容压入容器中
vector<string> words;
while(getline(in,line))
{
words.push_back(line);
}
in.close();
for(string i : words)
{
cout<<i<<endl;
}
}
输出结果
另外
auto也是c++11的新标准
下面是官方文档:
C++11将auto用于实现自动类型判断。这要求进行显示初始化,让编译器能够将变量的 类型设置为初始值的类型。
auto maton = 112 ; // maton is type int
auto pt = &maton ; // pt id type int *
double fm ( double , int ) ;
auto pf = fm ; // pf is type double () (double , int )
关键字auto还可简化模板声明。
例:
如果 il 是一个std::initializer_list对象,则可将下述代码:
for ( std :: initializer_list < double > :: iterator p = il.begin() ; p != il.end() ; p++ )
替换为如下代码:
for ( auto p = il.begin() ; p != il.end() ; p ++ )
auto maton = 112 ; // maton is type int
auto pt = &maton ; // pt id type int *
double fm ( double , int ) ;
auto pf = fm ; // pf is type double (*) (double , int )
例:
如果 il 是一个std::initializer_list对象,则可将下述代码:
for ( std :: initializer_list < double > :: iterator p = il.begin() ; p != il.end() ; p++ )
替换为如下代码:
for ( auto p = il.begin() ; p != il.end() ; p ++ )*