遍历

#include <iostream>
#include <vector>


int main(int argc, char *argv[])
{
    std::vector<int> vec;

    for (int i = 1; i <= 9; i++) {
        vec.push_back(i);
    }

    // for 区间遍历,可用在任意一种有迭代器的类
    for (auto val : vec) {
        std::cout << val << " ";
    }
    std::cout << std::endl;

    // 使用 for_each + 匿名函数
    for_each(vec.cbegin(), vec.cend(),
            [](const int &val) { std::cout << val << " "; });
    std::cout << std::endl;

    // 迭代器,使用 auto 关键字,少打几个字
    for (auto pval = vec.cbegin(); pval != vec.cend(); pval++) {
        std::cout << *pval << " ";
    }
    std::cout << std::endl;

    // 迭代器,注意 cbegin() 返回的是最后一个位置的后一个位置
    for (std::vector<int>::const_iterator pval = vec.cbegin();
            pval != vec.cend(); pval++) {
        std::cout << *pval << " ";
    }
    std::cout << std::endl;

    // 反向迭代器
    for (auto pval = vec.crbegin(); pval != vec.crend(); pval++) {
        std::cout << *pval << " ";
    }
    std::cout << std::endl;

    // C 风格
    for (int i = 0; i < vec.size(); i++) {
        std::cout << vec[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}