c++11新版本"for循环的使用"和"auto的使用"

贪吃蛇游戏的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 ++ )*

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值