karma( 업 )/C_C++

02. 범위기반 for문( C++11으로 가자 )

생짜 2018. 11. 1. 14:16

///////////////////////////////////////////////////////////////

// 02. 범위기반 for 문 Example

// C++11은 Java나 C#에서 제공하는 범위기반 for문을 제공한다.

// * for 루프가 간단해 짐

// * 루프의 순회값(i)의 초기값을 정해줄 필요가 없다.

// * 배열의 길이를 지정해주지 않아도 된다.

// * 언제까지 순회(범위)해야 할지 지정할 필요가 없다.

///////////////////////////////////////////////////////////////////

#include <iostream>

#include <vector>

using namespace std;


int main()

{

    vector<int> vInt;

    for(auto i=0; i<10; ++i)

    {

        vInt.push_back(i);

    }


    //C++03 표준

    cout << "C++03 standard"<<endl;

    std::vector<int>::const_iterator it;

    for(it = vInt.begin(); it != vInt.end(); ++it)

    {

        std::cout << *it << std::endl;

    }


    //C++11 표준

    cout<< "C++11 standard"<<endl;

    for(auto i: vInt)  //for ( for-range-declaration : expression )

    {

        std::cout << i <<std::endl;

    }


    getchar();

    return 0;

}