C++11新增加的兩種 for 循環

1. 基於範圍(range-based)的 for 循環
#include <iostream>
#include <vector>
using namespace std;

int main() {
		double prices[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
    	for(double i: prices)
        		cout << i << " ";
    	cout << endl;


    	// 要修改數組的元素,則要使用引用變量
    	double pricess[5];
    	for(double &i: pricess)
        		cin >> i;

    	for(double i: pricess)
        		cout << i << " ";
    	cout << endl;

    	vector<int> nums;
    	for(int i = 0; i < 6; i++)
        		nums.push_back(10 + i);

    	for(int i : nums) {
        		cout << i << " ";
    	}
    	cout << endl;

    	return 0;
}
2. for_each 語句

for_each 算法中使用了“迭代器”(指針),其內部包含了自增操作的概念,所以不需要寫上 ++p 指針,但是對於該循環體得給出其界限範圍. 很多地方使用 for_each 語法來使用 STL 遍歷容器.
需要包含頭文件 #include <algorithm>

嚴格來說第三個參數的要求是 C++ concepts: FunctionObject,所以傳入的參數可以爲下列類型之一:

  • 1.函數指針/引用;
  • 2.含有operator ()成員的類型對象(functor),且std::for_each具有訪問該成員的權限;
  • 3.lambda.

比如傳入“函數名”其實是第一條。另外,傳入的對象必須可以以解引用的迭代器爲唯一參數調用。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void myPrint(int& elem) {
    	cout << elem << " ";
}

int main() {
    	vector<int> nums;
    	for(int i = 0; i < 6; i++)
        		nums.push_back(10 + i);

    	// 1.傳入global function name
    	for_each(nums.begin(), nums.end(), myPrint);
    	cout << endl;
    
    	// 未完待續

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