프로그래밍응용/Modern & STL
Iterator 사용 방법 예시
photoner
2021. 1. 5. 19:51
728x90
반응형
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | #include <iostream> #include <vector> using namespace std; int main(void) { // vector 값 10개를 추가한다. vector<int> vec; for (int i = 0; i < 10; i++) vec.push_back(i); // iterator를 이용한 순회 vector<int>::iterator it; for (it = vec.begin(); it != vec.end(); it++) cout << *it << endl; cout << endl; // iterator를 포인터처럼 사용할 수 있다. it = vec.begin(); cout << it[3] << endl; // 3 cout << *(it+3) << endl; // 3 cout << *(++it) << endl; // 1 cout << *it++ << endl; // 1 cout << *it << endl; // 2 it[0] = 100; cout << it[0] << endl; // 100 *(it+1) = 200; cout << *(it + 1) << endl; // 200 cout << it[1] << endl; // 200 cout << "--------------------------------------------------" << endl; vector<int>::const_iterator cit = vec.begin(); for (cit = vec.begin(); cit != vec.end(); cit++) cout << *cit << endl; cout << "--------------------------------------------------" << endl; cout << cit[-1] << endl; cout << cit[-2] << endl; cout << cit[-3] << endl; cout << cit[-4] << endl; cout << cit[-5] << endl; cout << cit[-6] << endl; cout << cit[-7] << endl; cout << cit[-8] << endl; cout << cit[-9] << endl; cout << cit[-10] << endl; // cout << cit[-11] << endl; // 에러 ㅋ cout << "--------------------------------------------------" << endl; // vec.begin() 실제 요소, vec.end() 요소가 아님 -> 가리킬 수 없음 // 값이 반전되어 출력함 vector<int>::reverse_iterator rit; for (rit = vec.rbegin(); rit != vec.rend(); rit++) cout << *rit << endl; cout << "--------------------------------------------------" << endl; vector<int>::const_reverse_iterator crit; for (crit = vec.crbegin(); crit != vec.crend(); crit++) cout << *crit << endl; return 0; } | cs |
728x90
반응형