C++范围循环

范围循环用来遍历容器里的对象, C++11及以后的特性

  • 格式

    1
    2
    3
    4
    for(typename object: container)
    {
    loop body
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    void ForEach(const std::vector<int>& values, void(*func)(int))
    {
    for (int value : values) //范围循环
    {
    func(value);
    }
    }
    void PrintValue(int value)
    {
    std::cout << value << std::endl;
    }

    int main()
    {
    std::vector<int> values = { 1,2,3,4,5 };
    ForEach(values, PrintValue);

    std::cin.get();
    }

    比较常用的格式

    1
    2
    3
    4
    5
    6
    for(auto a: ai)
    ;
    for(auto &a: ai)
    ;
    for(auto const &a : ai)
    ;
  • © 2019-2022 Wendell
  • Powered by Hexo Theme Ayer

请我喝杯咖啡吧~

支付宝
微信