Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <unordered_map> // Essentially a hash map, doesn't store variables in any order
- int main()
- {
- std::vector<int> values = { 1, 2, 3, 4, 5 };
- for (int i = 0; i < values.size(); i++)
- {
- std::cout << values[i] << std::endl;
- }
- for (int value : values) // range-based for loop c++11
- {
- // value is the name of the current element we're iterating over while values is the whole collection
- std::cout << value << std::endl;
- }
- // Will run as long as iterator isn't equal to the end of this collection
- // 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.
- // Certain situations where you would want this: A) erasing an element but continue to iterate over the rest of the collection
- // B) Insert something into the middle based on a condition
- for (std::vector<int>::iterator it = values.begin(); // Normal iterator
- it != values.end(); it++)
- {
- std::cout << *it << std::endl;
- }
- // Cherno doesn't use using with iterators, only with the type sometimes
- using ScoreMap = std::unordered_map<std::string, int>;
- ScoreMap map;
- map["Cherno"] = 5;
- map["C++"] = 2;
- for (ScoreMap::const_iterator it = map.begin(); // Const iterator
- it != map.end(); it++)
- {
- auto& key = it->first;
- auto& value = it->second;
- std::cout << key << " = " << value << std::endl;
- }
- std::cout << std::endl;
- // Improved version of code immediately above
- for (auto kv : map) // Ranged-based for loops that use iterators
- {
- auto& key = kv.first;
- auto& value = kv.second;
- std::cout << key << " = " << value << std::endl;
- }
- std::cout << std::endl;
- // C++17 structured bindings method, even more improved
- // Can retrieve key value right inside of the statement
- for (auto [key, value] : map) // Structured bindings with maps
- std::cout << key << " = " << value << std::endl;
- std::cin.get();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement