#include <iostream>
#include <vector>
#include <unordered_map>
// iterators are essentialy a way to iterate over a collection of elements.
// super useful for complex data structure:unordered_map, unordered_set, tree...
int main(void)
{
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 i : values)//range-based for statement
{
std::cout << i << std::endl;
}
for (std::vector<int>::iterator it = values.begin(); it != values.end(); it++)
{
std::cout << *it << std::endl;
}
std::cout << "----------------------------" << std::endl;
using ScoreMap = std::unordered_map<std::string, int>;
ScoreMap map;
map["Cherno"] = 5;
map["C++"] = 2;
for (ScoreMap::const_iterator it = map.begin(); it != map.end(); it++)
{
auto& key = it->first;
auto& value = it->second;
std::cout << key << " = " << value << std::endl;
}
std::cout << "----------------------------" << std::endl;
for (auto kv : map)
{
auto& key = kv.first;
auto& value = kv.second;
std::cout << key << " = " << value << std::endl;
}
std::cout << "----------------------------" << std::endl;
for (auto [key, value] : map)// structure binding.
{
std::cout << key << " = " << value << std::endl;
}
std::cin.get();
}
【Cherno的C++视频】Iterators in C++
最新推荐文章于 2024-08-26 17:31:44 发布