Advertisement
Ginsutime

Cherno Iterator Basics

Feb 23rd, 2022
849
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_map> // Essentially a hash map, doesn't store variables in any order
  4.  
  5. int main()
  6. {
  7.     std::vector<int> values = { 1, 2, 3, 4, 5 };
  8.  
  9.     for (int i = 0; i < values.size(); i++)
  10.     {
  11.         std::cout << values[i] << std::endl;
  12.     }
  13.  
  14.     for (int value : values) // range-based for loop c++11
  15.     {
  16.         // value is the name of the current element we're iterating over while values is the whole collection
  17.         std::cout << value << std::endl;
  18.     }
  19.  
  20.     // Will run as long as iterator isn't equal to the end of this collection
  21.     // Why use this over a range-based for loop since the other is shorthand? You wouldn't aside from wanting to manipulate position of iterator.
  22.     // Certain situations where you would want this: A) erasing an element but continue to iterate over the rest of the collection
  23.     // B) Insert something into the middle based on a condition
  24.     for (std::vector<int>::iterator it = values.begin(); // Normal iterator
  25.         it != values.end(); it++)
  26.     {
  27.         std::cout << *it << std::endl;
  28.     }
  29.  
  30.     // Cherno doesn't use using with iterators, only with the type sometimes
  31.     using ScoreMap = std::unordered_map<std::string, int>;
  32.     ScoreMap map;
  33.     map["Cherno"] = 5;
  34.     map["C++"] = 2;
  35.  
  36.     for (ScoreMap::const_iterator it = map.begin(); // Const iterator
  37.         it != map.end(); it++)
  38.     {
  39.         auto& key = it->first;
  40.         auto& value = it->second;
  41.  
  42.         std::cout << key << " = " << value << std::endl;
  43.     }
  44.  
  45.     std::cout << std::endl;
  46.  
  47.     // Improved version of code immediately above
  48.     for (auto kv : map) // Ranged-based for loops that use iterators
  49.     {
  50.         auto& key = kv.first;
  51.         auto& value = kv.second;
  52.  
  53.         std::cout << key << " = " << value << std::endl;
  54.     }
  55.  
  56.     std::cout << std::endl;
  57.  
  58.     // C++17 structured bindings method, even more improved
  59.     // Can retrieve key value right inside of the statement
  60.     for (auto [key, value] : map) // Structured bindings with maps
  61.         std::cout << key << " = " << value << std::endl;
  62.  
  63.     std::cin.get();
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement