天天看點

C++11 2.0 autoauto

auto

假如你不想寫被建立對象的類型,或者你不知道等式傳回值類型是什麼,你可以使用auto關鍵字,讓編譯器自動确定變量類型。

代碼示例:

#include <iostream>
#include <list>
#include <string>
using namespace std;

int main(){
/*
	/
	list<string> c;
	...
	list<string>::iterator ite;
	ite = find(c.begin(),c.end(),target);
	/
	//假如你不想寫list<string>::iterator ite;這句話,那麼你可以寫成下面的語句
	///
	list<string>c;
	...
	auto ite = find(c.begin(), c.end(), target);
	///
	
	//但是不能寫成下面的形式
	list<string>c;
	...
	auto ite
	ite = find(c.begin(), c.end(), target);
	*/
	list<string>c;
	c.push_back("張飛");
	c.push_back("劉備");
	c.push_back("關羽");
	c.push_front("趙雲");
	auto ite = find(c.begin(), c.end(), "關羽");
	cout << *ite << endl;
}

	system("pause");
	return 0;
           

執行結果:

C++11 2.0 autoauto

繼續閱讀