C++11常見新特性

1. auto關鍵字

auto關鍵字起到的作用是自動類型判斷。在聲明變量的時候根據左值可以判斷出類型並自動爲此變量選擇相匹配的類型。比如:

#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <functional>
using namespace std;


int main()
{
	int a = 10;
	auto b = a;
	cout << b << endl;
	system("pause");
	return 0;
}

上面的代碼中編譯器就會判斷a的類型並賦予給b。但是顯然如果單純這麼用,編譯器已經知道上述的左值的類型了,其實並沒有用的必要。auto一般可以用於迭代器,類模板這種不好判斷參數類型的地方:

#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <functional>
using namespace std;


int main()
{
	map<int, int> mp;
	mp.insert(make_pair(1, 3));
	mp.insert(make_pair(5, 7));
	mp.insert(make_pair(10, -1));
	mp.insert(make_pair(3, 5));
	mp.insert(make_pair(2, 4));

	for (auto m = mp.begin(); m != mp.end(); m++){
		cout << m->first << " " << m->second << endl;
	}
	system("pause");
	return 0;
}

或者類模板的情景:

#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <functional>
using namespace std;

/*
在類模板場景中,因爲不能確定模板對應的類型,用auto在實際編譯過程中確定,這樣會很方便。
*/
template<typename T>
class testauto{
public:
	testauto(){}
	~testauto(){}
	void print(T t1, T t2);
};

template<typename T>
void testauto<T>::print(T t1, T t2){
	auto res = t1 * t2;//不知道T實際什麼類型,所以用auto代替
	cout << res << endl;
}

int main()
{
	testauto<int> t;
	int a = 5;
	int b = 10;
	t.print(a, b);
	system("pause");
	return 0;
	/*
	輸出:50
	*/
}

需要注意的是,和const常量一樣,auto定義一個變量初始化。auto a = 10;是可以的,但是單獨定義一個auto a;是不行的。

 

2. 範圍for語句:

for語句是一種循環語句,本身很常見。但是範圍for語句更加簡化了for循環遍歷的過程。它可以和auto連用,也可以和單獨的類型一起使用。舉例如下:

#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <functional>
using namespace std;

int main()
{
	vector<int> vec{ 1, 2, 3, 4, 5, 6, 7 };
	for (int num : vec){
		cout << num << " ";
	}
	cout << endl;
	vector<char> vecchar{ '1', 'a', 'v', 'c' };
	for (auto c : vecchar){
		cout << c << " ";
	}
	cout << endl;
	system("pause");
	return 0;
	/*
	輸出:
	1 2 3 4 5 6 7
	1 a v c
	*/
}

3. decltype

decltype可以用於求變量和函數表達式的類型。如下:

#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <functional>
using namespace std;

int func(int a, int b){
	return a + b;
}

int main()
{
	int a = 5;
	double b = 10;
	decltype(a) a1;//a1類型是int
	decltype(b) b2;//b2類型是double
	decltype(func(a, b)) c;//c類型是int,是函數返回值的類型
	system("pause");
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章