karma( 업 )/C_C++

01. auto( C++11으로 가자 )

생짜 2018. 11. 1. 13:43

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

// 01. auto Example

// C++11의 auoto 관련 예제

// JavaScript의 'var' 와 같은 기능을 함

// STL 컨테이터에서 반복자 등을 지정할 때는 'auto' 키워드가 입력해야 할 코드 양을 상당히 줄여줌

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


#include <iostream>

#include <vector>

using namespace std;


int main(int argc, char** argv)

{

    vector<int> vInt;

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

    {

        vInt.push_back(i);

    }


    //C++03 표준

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

    vector<int>::iterator it = vInt.begin(); // STL의 vector을 사용하기 위해 vector의 iterator을 선언

    while(it != vInt.end())

    {

        cout << *it<<endl;

        it++;

    }


    //C++11 표준

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

    auto it2 = vInt.begin(); //auto 키워드로 선언하면 컴파일러가 자동으로 vector iteraotr을 인식, 

                              //타수가 줄어든다

    while(it2 != vInt.end())

    {

        cout<< *it2<<endl;

        it2++;

    }


    getchar();

    return 0;

}


cpp11_auto.cpp