nakka soft world !

반복자 (STL iterator) 본문

프로그래밍언어/C++

반복자 (STL iterator)

nakka 2017. 3. 19. 20:13
728x90

반복자 (STL iterator)


1, 개념

#include <iostream>
#include <vector>

using namespace std;


int main()

{

int x[10] = { 1,2,3,4,5,6,7,8,9,10};  //배열

int* p = x;

++p;

cout << *p << endl;


vector<int> v = ( 1,2,3,4,5,6,7,8,9,10 }; // STL Vector


auto p2 = v.begin(); // p2는  v의 첫번째 요소를 가르키는 포인터 역할

// vector<int>::iterator p2 = v.begin();

cout << *p2 << endl;  // 1

++p2;

cout << *p2 << endl;  // 2

}


2.

int main()

{

vector<int> v = ( 1,2,3,4,5,6,7,8,9,10 };


auto p1 = v.begin();  // == auto p1 = begin(v);(일반함수)

auto p2 = v.end(); // 마지막 다음 요소를 가르 킴. == auto p2 =  end(v);(일반함수)

// cout << *p2 << endl;;  // runtime error

// 일반 함수의 장점. int v[10] = ( 1,2,3,4,5,6,7,8,9,10 }; 으로 변경되어도 code 수정 불필요 - 단, 일반함수는 C++11부터 지원


auto


while(p1 != p2)

{

cout << *p1 << endl;

++p1;

}

}



3. 열거

#include <iostream>
#include <vector>

using namespace std;


int main()

{

vector<int> v = ( 1,2,3,4,5,6,7,8,9,10 }; // 연속된 메모리


// 열거 1. [] 연산자 사용 - 단 list불가능.

for(int i = 0; i< v.size(); i++)

cout << v[i] << endl;


// 열거 2.

for( auto n : v )

cout << n << endl;


// 열거 3.

auto p = begin(v); // v.begin()


while (p!= end(v))   // while (p!= p+5) - 5개만 열거할 때는 이렇게.

{

cout << *p << endl;

++p;

}

}



4. 장점.

#include <iostream>
#include <vector>

#include <list>

#include <algorithm>

using namespace std;


int main()

{

list<int> s = {1,2,3,4,5,6,7,8,9,10}; //각 요소가 떨어져 있음.

vector<int> v = {1,2,3,4,5,6,7,8,9,10}; // 연속된 메모리


auto p1 = s.begin();

auto p2 = v.begin();


++p1;

++p2;

}

// 장점 :  컨테이너 내부의 구조에 관계없이 동일한 방법으로 열거가 가능하다.


auto p = s.front(); // front 멤버 함수는 반복자가 아닌 첫번째 요소를 꺼내는 코드입닏.

728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

알고리즘의 정책 변경  (0) 2017.03.19
STL 알고리즘 ( algorithm )  (0) 2017.03.19
컨테이너 (Container)  (0) 2017.03.19
STL (Standard Template Library)  (0) 2017.03.19
String 클래스 만들기  (0) 2017.03.19
Comments