天天看點

C++11 for的使用

如果你隻是想對集合或數組的每個元素做一些操作,而不關心下标、疊代器位置或者元素個數,那麼這種foreach的for循環将會非常有用

for ( range_declaration : range_expression) loop_statement//聲明變量、變量範圍

std::vector<int> int_vec;

int_vec.push_back(1);

int_vec.push_back(2);

//如果要修改int_vec中的元素,将變量x聲明為 int& 即可

for (int x: int_vec)

{

    std::cout << x << endl;

}

1、周遊字元串

std::string str = “hello, world”;  

for(auto ch : str) {  

     std::cout << ch << std::endl;  

} 周遊str,輸出每個字元,同時用上auto,更友善。

2、周遊數組

int arr[] = {1, 2, 3, 4};  

for(auto i : arr) {  

     std::cout<< i << std::endl;  

} 不用知道數組容器的大小,即可友善的周遊數組。

3、周遊STL vector容器

std::vector<std::string> str_vec = {“i”, “like”,  "google”};  

for(auto& it : str_vec) {  

     it = “c++”;  

}  在這段程式中,可以傳回引用值,通過引用可以修改容器内容。然後用到了初始化清單

4、周遊STL map容器

std::map<int, std::string> hash_map = {{1, “c++”}, {2, “java”}, {3, “python”}};  

for(auto it : hash_map) {  

     std::cout << it.first << “\t” << it.second << std::endl;  

} 周遊map傳回的是pair變量,不是疊代器。

5、for range功能

for(auto it = vec_int.begin(); it!= vec_int.end(); ++it) {  

    cout << *it << "\t";  

}  

測試後for range也需要滿足這四個條件:

1、實作begin()

2 、實作end()

3 、實作 operator++()

4 、實作 operator!=(class& other)

c++

繼續閱讀