C++11 for


ex1: traverse the string
  1. std::string str = “hello, world”;  
  2. for(auto ch : str) {  
  3.      std::cout << ch << std::endl;  
  4. }  

Traversing str, outputting each character, and using auto at the same time is simply more powerful.

ex2: traverse the array
  1. int arr[] = {1, 2, 3, 4};  
  2. for(auto i : arr) {  
  3.      std::cout<< i << std::endl;  
  4. }  

You can easily traverse an array without knowing the size of the array container.

ex3: Traverse the stl container
  1. std::vector<std::string> str_vec = {“i”, “like”,  "google”};  
  2. for(auto& it : str_vec) {  
  3.      it = “c++”;  
  4. }  

In this program, a reference value can be returned, and the contents of the container can be modified by reference. Then the initialization list is used, which will be introduced in the next article.

ex4: Traverse stl map 
  1. std::map<int, std::string> hash_map = {{1, “c++”}, {2, “java”}, {3, “python”}};  
  2. for(auto it : hash_map) {  
  3.      std::cout << it.first << “\t” << it.second << std::endl;  
  4. }  

Traversing the map returns a pair variable, not an iterator.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325444138&siteId=291194637