본문 바로가기

컴퓨터공학/자료구조

[C++] Set 자료구조 역순으로 자료 참조하기

 프로그래머스 코딩을 하다가, Set 마지막 원소를 참조해서 답을 찾는 문제가 있었다. 이 경우에, 역순 반복자를 쓰면 손쉽게 해결할 수 있다. 다음 예제를 보면 충분히 이해가 갈 것이다.

 

 반복자를 사용하는 모든 자료 구조에서, 마지막 원소를 찾기 위해서 기본 반복자를 사용하지말고, 역순 반복자를 사용하면 O(1)만에 마지막 원소를 찾을 수 있다.

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
// set::rbegin/rend
#include <iostream>
#include <set>
using namespace std;
 
int main()
{
    int myints[] = { 21,64,17,78,49 };
    set<int> myset(myints, myints + 5);
 
    //Iterator
    set<int>::iterator it;
 
    std::cout << "myset contains:";
    for (it = myset.begin(); it != myset.end(); ++it)
        cout << ' ' << *it;
    cout << '\n';
 
    // Reverse iterator
    set<int>::reverse_iterator rit;
 
    std::cout << "myset contains:";
    for (rit = myset.rbegin(); rit != myset.rend(); ++rit)
        cout << ' ' << *rit;
 
    cout << '\n';
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter