페이지

Include Lists

2017년 3월 1일 수요일

Ranged For


 What
   - 새로운 방식의 반복문 학습

 Why
   - c++11이상을 사용한다면, 익숙해지자.

 Usage
   - 기존의 For와 호환해서 사용할 것




C++ 에서 사용하는 For Loop문의 형태는 아래와 같다 (while 제외)
  - for / for_each / for(ranged_for)

  1. for 

    - 가장 범용적으로 알려진 for loop의 형태는 다음과 같다.
    - for ( init-expression ; cond-expression ; loop-expression )
   statement

  2. for each
    - c++ 표준이 아닌, Microsoft visual c++ 만의 문법
    - for each (type identifier in expression)
  statements

  3. std::for_each
    - template<class InputIterator, class Function>
           Function for_each(
           InputIterator _First,
           InputIterator _Last,
           Function _Func
           );

    - Iterator 기반의 동작 함수

    - Loop 중단이 안되는 문제.

  4. for (ranged based for)
    - Vector, array 등의 Collection 기반의 동작 함수.
    - c++11 이상에서만 지원
    - Stl 과 완벽 호환
    - for ( for-range-declaration : expression )
       statement
    - 동작 방식은, array 기반은 범위를 인식하고, stl은 begin, end를 인식하여 동작.
      그래서 new / malloc등으로 동적 할당된 메모리에 대해서는 사용이 불가.
      ( 직접 만들어 줘야함.)
      또한, begin/end를 가지고 있는 않은 객체는 아래와 같은 에러가 발생
          error C3312: no callable 'begin' function found for type 'int'
          error C3312: no callable 'end' function found for type 'int'



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>
int main() cout{
    std::vector<int> v = { 012345 };
    for (const int& i : v)  // access by const reference
        cout std:: << i << ' ';
    cout std:: << '\n';
    for (auto i : v) // access by value, the type of i is int
        cout std:: << i << ' ';
    cout std:: << '\n';
    for (auto&& i : v) // access by reference, the type of i is int&
        cout std:: << i << ' ';
    cout std:: << '\n';
    for (int n : {012345}) // the initializer may be a braced-init-list
        cout std:: << n << ' ';
    cout std:: << '\n';
    int a[] = { 012345 };
    for (int n : a) // the initializer may be an array
        cout std:: << n << ' ';
    cout std:: << '\n';
    for (int n : a)
        cout std:: << 1 << ' '// the loop variable need not be used
    std:: << '\n';
}
cs

댓글 없음:

댓글 쓰기