반응형

첫번째 원소가 기준에 따라 가장 큰 컨테이너 어댑터

힙과 유사

원소가 빠져나갈 때, top(back)에서부터 pop

멤버함수

생성

#include <iostream>
#include <queue>

using namespace std;

class cmp{
    bool reverse;
public:
    cmp(const bool& rev = false){
        reverse = rev;
    }
    bool operator()(const int& lhs, const int&rhs){
        if(reverse)
            return (lhs > rhs);
        else
            return (lhs < rhs);
    }
};

int main(void){
    int arr[] = {1, 3, 2, 4};

    priority_queue<int> pq1;
    priority_queue<int> pq2(arr, arr+4);
    // 4 3 2 1
    priority_queue<int, vector<int>, greater<int> > pq3(arr, arr+4);
    // 1 2 3 4
    priority_queue<int, vector<int>, cmp > pq4(arr, arr+4);
    // 4 3 2 1
    priority_queue<int, vector<int>, cmp > pq5(arr, arr+4, cmp(true));
    // 1 2 3 4
}

멤버함수

  • empty()
  • size()
  • top()
  • push()
  • pop()
  • emplace() * C++11
  • swap() * C++11
#include <iostream>
#include <queue>

using namespace std;

int main(void){
    priority_queue<int> pq;

    for(int i = 1; i < 10; ++i)
        pq.push(i);
    cout << pq.size() << '\n';
    // 9

    while(!pq.empty()){
        cout << pq.top() << ' ';
        pq.pop();
    }
    cout << '\n';
    // 9 8 7 6 5 4 3 2 1
}
반응형

'C++' 카테고리의 다른 글

[C++] STL - queue  (0) 2020.12.21
[C++] 반복자  (0) 2020.12.01
[C++] string library  (0) 2020.11.27
[C++] cout 부동소수점 다루기  (0) 2020.11.20
[C++] STL - deque  (0) 2020.11.13
반응형

FIFO 문맥에서 동작하기 위해 설계된 컨테이너 어뎁터

멤버함수

생성

#include <iostream>
#include <deque>
#include <list>
#include <queue>

using namespace std;

int main(void){
    deque<int> d(3, 100);
    list<int> l(2, 50);

    queue<int> q1;
    queue<int> q2(d);
    queue<int, list<int>> q3;
    queue<int, list<int>> q4(l);
}

멤버함수

  • empty()
  • size()
  • front()
  • back()
  • push()
  • pop()
  • emplace() * C++11
  • swap() * C++11
#include <iostream>
#include <queue>

using namespace std;

int main(void){
    queue<int> q;

    for(int i = 1; i < 10; ++i)
        q.push(i);
    cout << q.back() << '\n';
    // 9
    cout << q.size() << '\n';
    // 9

    while(!q.empty()){
        cout << q.front() << ' ';
        q.pop();
    }
    cout << '\n';
    // 1 2 3 4 5 6 7 8 9
}
반응형

'C++' 카테고리의 다른 글

[C++] STL - priority_queue  (0) 2020.12.21
[C++] 반복자  (0) 2020.12.01
[C++] string library  (0) 2020.11.27
[C++] cout 부동소수점 다루기  (0) 2020.11.20
[C++] STL - deque  (0) 2020.11.13
반응형

STL 컨테이너에 저장된 요소를 반복적으로 순회하여, 각각의 요소에 대한 접근을 제공하는 객체


특징

  • 가리키는 요소의 값에 접근
  • 반복자 사이의 대입 연산, 비교 연산
  • 가리키는 요소의 주변 요소로 이동

종류

  • 입력 반복자
  • 출력 반복자
  • 순항향 반복자
  • 양방향 반복자
  • 임의 접근 반복자

입력 반복자

컨테이너로부터 값을 읽는 데 사용(변경 X)

증가 연산자(++)를 사용하여 순방향으로만 이동 가능

참조 연산자(*)를 사용하여 요소 참조

ex) find()

출력 반복자

컨테이너의 값을 변경하는 데 사용(읽기 X)

증가 연산자(++)를 사용하여 순방향으로만 이동 가능

참조 연산자(*)를 사용하여 한 번 요소 변경 가능

ex) copy()

순방향 반복자

입출력 모두 가능 -> 다중 패스 알고리즘에 사용 가능

증가 연산자(++)를 사용하여 순방향으로만 이동 가능

참조 연산자(*)를 사용하여 요소를 참조하거나 변경 가능

ex) replace()

양방향 반복자

입출력 모두 가능

증감연산자(++/--)를 사용하여 양방향 이동 가능

참조 연산자(*)를 사용하여 요소를 참조하거나 변경 가능

ex) reverse()

임의 접근 반복자

양방향 반복자의 모든 기능 포함 + 일반 포인터가 하는 거의 모든 일

증감연산자(++/--)를 사용하여 양방향 이동 가능

첨자 연산자([])를 통해 임의의 요소에 접근 가능

산술 연산자(+, -)와 관계 연산자(<, <=, >, >=) 사용 가능

ex) sort()


계층

반복자는 계층적으로 분류

다양한 반복자를 사용하여 알고리즘의 적용 조건을 제한


기타 반복자

스트림 반복자

반복자 연산을 통해 알고리즘이 입출력 스트림에 쉽게 접근

입출력 스트림을 각각 입출력 반복자로 변환하는 방식으로 제공

istream_iterator, ostream_iterator 클래스 템플릿에서 제공

vector<int> vc = {1, 2, 3, 4, 5};
copy(vc.begin(), vc.end(), ostream_iterator<int>(cout));
// 12345
cout<<endl;
copy(vc.begin(), vc.end(), ostream_iterator<int>(cout));
// 1 2 3 4 5

삽입 반복자

그 요소의 위치에 새로운 값을 삽입 cf) 출력 반복자: 가리키는 요소의 값 덮어쓰기

  • insert_iterator - insert() : 해당 컨테이너의 특정 위치에 삽입, 모든 컨테이너에 사용 가능
  • back_insert_iterator - push_back(): 해당 컨테이너의 뒤쪽에 삽입, 시퀀스 컨테이너(vector, list, deque)에 사용 가능
  • front_insert_iterator - push_front(): 해당 컨테이너의 앞쪽에 삽입, list, deque에 사용 가능
list<int> ls = {10};
ls.push_back(20);
ls.push_front(30);
copy(ls.begin(), ls.end(), ostream_iterator<int>(cout, " "));
// 30 10 20

역방향 반복자

순방향 반복자와 반대 방향으로 동작하는 반복자

역방향 반복자의 증가 연산자(++)은 순방향 반복자의 역방향으로 이동

rbegin(), rend() 멤버 함수를 사용하면 자동으로 reverse_iterator 반환

list<int> ls = {10, 20, 30};
copy(ls.rbegin(), ls.rend(), ostream_iteraot<int>(cout, " "));
// 30 20 10

상수 반복자

반복자가 가리키는 값의 변경이 불가능한 반복자(이동하여 다른 요소를 가리키는 것은 가능)

const_iterator 타입

list<int> ls = {10, 20, 30};
list<int>::iterator iter;
list<int>::const_iterator citer;

iter = ls.begin();
*iter = 100;
citer = ls.end();
// *citer = 300;

for(citer = ls.begin(); citer != ls.end(); ++citer)
    cout<<*citer<<" ";
// 100 20 30
반응형

'C++' 카테고리의 다른 글

[C++] STL - priority_queue  (0) 2020.12.21
[C++] STL - queue  (0) 2020.12.21
[C++] string library  (0) 2020.11.27
[C++] cout 부동소수점 다루기  (0) 2020.11.20
[C++] STL - deque  (0) 2020.11.13
반응형

문자열을 표현하는 객체

생성

#include <iostream>
#include <string>

using namespace std;

int main(){
    string s0("string");    // string
    string s1;    //
    string s2(s0);    // string
    string s3(s0, 2, 3);    // rin
    string s4("abcdefg", 4);    // abcd
    string s5(5, 'A');    // AAAAA
    string s6(s0.begin(), s0.begin()+3);    // str
}

반복자

  • begin()
  • end()
  • rbegin()
  • rend()
  • cbegin() * C++11
  • cend() * C++11
  • crbegin() * C++11
  • crend() * C++11
#include <iostream>
#include <string>

using namespace std;

int main(void){
    string str("Test string");
    for(string::iterator it = str.begin(); it != str.end(); ++it)
        cout << *it;
    cout << endl;
    // Test string
    for(string::reverse_iterator rit = str.rbegin(); rit != str.rend(); ++rit)
        cout << *rit;
    cout << endl;
    // gnirts tseT

    return 0;
}

용량

  • size()
  • length()
  • max_size()
  • resize()
  • capacity()
  • reserve()
  • clear()
  • empty()
  • shrink_to_fix() * C++11
#include <iostream>
#include <string>

using namespace std;

int main(void){
    string str("Test string");
    cout << str.size() << endl;
    // 11
    cout << str.length() << endl;
    // 11
    cout << str.max_size() << endl;
    // 1073741823

    str.resize(str.size()+2, '!');
    cout << str << endl;
    // Test string!!
    str.resize(4);
    // Test

    cout << str.capacity() << endl;
    // 15
}

요소 접근

  • []
  • at()
  • back() * C++11
  • front() * C++11
#include <iostream>
#include <string>

using namespace std;

int main(void){
    string str("Test string");
    int len = str.length();
    for(int i = 0; i < len; ++i)
        cout << str[i];
    cout << endl;
    // Test string
    for(int i = 0; i < len; ++i)
        cout << str.at(i);
    cout << endl;
    // Test string
    cout << str.front() << endl;
    // g
    cout << str.back() << endl;
    // T
}

제어

  • +=
  • append()
  • push_back()
  • pop_back() * C++11
  • assign()
  • insert()
  • erase()
  • replace()
  • swap()
#include <iostream>
#include <string>

using namespace std;

int main(void){
    string alpha("abcde");
    string number("12345");
    number += "678";
    number += alpha;
    cout << number << endl;
    // 12345678abcde

    string str;
    string str2="abcde";
    string str3="12345";
    str.append(str2);    // abcde
    str.append(str3, 2, 2);    // abcde34
    str.append(" ABCDE", 3);    // abcde34 AB
    str.append(10, '.');    // abcde34 AB.....

    alpha.push_back('f');
    // abcdef
    number.pop_back();
    // 1234567

    str.assign(str2);
    // abcde
    str.assign(str3, 3, 2);
    // 45
    str.assign("ABCDE", 3);
    // ABC
    str.assign(5, '!');
    // !!!!!
    str.assign(number.begin()+1, number.end()-1);
    // 23456

    str.insert(3, "abc");
    // 234abc56
    string::iterator it = str.insert(str.begin()+2, ' ');
    // 23 4abc56
    str.insert(it+3, str3.begin(), str3.begin()+2);
    // 23 4aABbc56

    str.erase(2, 4);
    // 23Bbc56
    str.erase(str.begin()+3, str.begin()-2);
    // bc

    str.assign(str2);
    // abcde
    str.replace(2, 2, str3);
    // ab12345e
    str.replace(str.begin()+1, str.begin()+3, "ABCDE");
    // aABCDE2345e
    str.replace(str.begin(), str.end()-2, "zxcv", 2);
    // zx5e
    str.replace(str.begin()+2, str.end(), 4, '!');
    // zx!!!!

    cout << str2 << ' ' << str3 << endl;
    // abcde 12345
    str2.swap(str3);
    cout << str2 << ' ' << str3 << endl;
    // 12345 abcde

    return 0;
}

연산

  • c_str
  • data
  • get_allocator
  • copy
  • find
  • rfind
  • find_first_of
  • find_last_of
  • find_first_not_of
  • find_last_not_of
  • substr
  • compare
#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main(void){
    string str("qwertyuiop asdfghjkl zxcvbnm");
    char *cstr = new char[str.length()+1];
    strcpy(cstr, str.c_str());

    char *p = strtok(cstr, " ");
    while(p != 0){
        cout << p << '\n';
        p = strtok(NULL, " ");
    }
    // qwertyuiop
    // asdfghjkl
    // zxcvbnm
    delete[] cstr;

    char buffer[20];
    string str1("Test string");
    int len = str1.copy(buffer, 6, 5);
    buffer[len] = 0;
    cout << buffer << '\n';
    // string

    string str2("abcde");
    string str3 = str2.substr(2, 2);
    cout << str3 << '\n';
    // cd

    return 0;
}
반응형

'C++' 카테고리의 다른 글

[C++] STL - queue  (0) 2020.12.21
[C++] 반복자  (0) 2020.12.01
[C++] cout 부동소수점 다루기  (0) 2020.11.20
[C++] STL - deque  (0) 2020.11.13
[C++] STL - stack  (0) 2020.10.28
반응형

cout을 통해 출력하는 경우 유효숫자 6자리까지만 출력되는 것을 확인할 수 있다.

 

유효숫자 수를 조절하기 위해 cout.precision()에 원하는 자리수를 인자로 넣어준다.

cout << fixed를 통해 소숫점 아래 출력 범위를 고정할 수 있다.

#include <iostream>

using namespace std;

int main(void){
    int a, b;
    cin >> a >> b;
	// 4 7

    cout << 0.5714285714 << endl;
    // 0.571429

    double d = 0.5714285714;
    cout << d << endl;
    // 0.571429

	cout << (double)a/b << endl;
    // 0.571429

    cout.precision(10);
    cout << fixed << (double)a/b << endl;
    // 0.5714285714
}

 

참고 ) 백준 - 1008 : A/B

반응형

'C++' 카테고리의 다른 글

[C++] 반복자  (0) 2020.12.01
[C++] string library  (0) 2020.11.27
[C++] STL - deque  (0) 2020.11.13
[C++] STL - stack  (0) 2020.10.28
[C++] STL - vector  (0) 2020.10.28
반응형

시퀀스 컨테이너

double ended queue

요소가 추가되거나 삭제될 때마다 자동으로 메모리를 재할당하여 크기를 동적으로 변경

element가 흩어져 있다. cf ) deque - 단일 배열

멤버 함수

생성

#include <deque>

using namespace std;

int main(){    
    deque<int> first;    // 빈 데크
    deque<int> second(4, 100);    // 4개의 int(값 100)
    deque<int> third(second.begin(), second.end());    // 반복자 사용
    deque<int> fourth(third);    // 벡터 복사

    int myints[] = {1, 2, 3, 4};
    deque<int> fifth(myints, myints + sizeof(myints)/sizeof(int));    // 반복자 사용2(배열)

    return 0;
}

반복자

  • begin() / end()
  • rbegin() / rend()
  • cbegin() / cend() : const * C++11
  • crbegin() / crend() * C++11
#include <iostream>
#include <deque>

using namespace std;

int main(){
    deque<int> dq;
    for(int i = 1; i <= 5; ++i)
        dq.push_back(i);

    for(deque<int>::iterator it = dq.begin(); it != dq.end(); ++it)
        cout<<*it<<' ';
    cout<<'\n';
    // 1 2 3 4 5
    for(deque<int>::reverse_iterator rit = dq.rbegin(); rit != dq.rend(); ++rit)
        cout<<*rit<<' ';
    cout<<'\n';
    // 5 4 3 2 1

    return 0;
}

용량

  • size()
  • max_size()
  • resize()
  • empty()
  • shrink_to_fit() * C++11
#include <iostream>
#include <deque>

using namespace std;

int main(){
    deque<int> dq;
    cout << dq.size() << endl;
    cout << dq.max_size() << endl;
    // 0
    // 536870911

    for(int i = 1; i <= 5; ++i)
        dq.push_back(i);
    cout << dq.size() << endl;
    cout << dq.max_size() << endl;
    // 5 {1, 2, 3, 4, 5}
    // 536870911

    dq.insert(dq.end(), 10, 100);
    cout << dq.size() << endl;
    cout << dq.max_size() << endl;
    // 15 {1, 2, 3, 4, 5, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100}
    // 536870911

    dq.pop_back();
    cout << dq.size() << endl;
    cout << dq.max_size() << endl;
    // 14 {1, 2, 3, 4, 5, 100, 100, 100, 100, 100, 100, 100, 100, 100}
    // 536870911

    return 0;
}
#include <iostream>
#include <deque>

using namespace std;

int main(){
    deque<int> dq;
    for(int i = 1; i < 10; ++i)
        dq.push_back(i);
    // 1 2 3 4 5 6 7 8 9

    dq.resize(5);
    // 1 2 3 4 5
    dq.resize(8, 100);
    // 1 2 3 4 5 100 100 100
    dq.resize(10);
    // 1 2 3 4 5 100 100 100 0 0

    return 0;
}
#include <iostream>
#include <deque>

using namespace std;

int main(){
    deque<int> dq;
    int sum = 0;

    for(int i = 1; i <= 10; ++i)
        dq.push_back(i);

    while(!dq.empty()){
        sum += dq.back();
        dq.pop_back();
    }

    cout << sum << endl;
    // 55

    return 0;
}

요소 접근

  • []
  • at()
  • front()
  • back()
#include <iostream>
#include <deque>

using namespace std;

int main(){
    deque<int> dq(10);
    int len = dq.size();
    for(int i = 0; i < len; ++i)
        dq.at(i) = i;

    for(int i = 0; i < len; ++i)
        cout << ' ' << dq.at(i);
    cout << endl;
    // 0 1 2 3 4 5 6 7 8 9

    cout << dq.front() << endl;
    // 0
    cout << dq.back() << endl;
    // 9

    return 0;
}

제어

  • assign()
  • push_back()
  • pop_back()
  • push_front()
  • pop_front()
  • insert()
  • erase()
  • swap()
  • clear()
  • emplace() * C++11
  • emplace_back() * C++11
  • emplace_front() * C++11

emplace vs insert: construct vs object

#include <iostream>
#include <deque>

using namespace std;

int main(){
    deque<int> first;
    deque<int> second;
    deque<int> third;

    first.assign(7, 100);    // 사이즈, 값
    second.assign(first.begin()+1, first.end()-1);    // 반복자, 반복자

    int arr[] = {12, 34, 56};
    third.assign(arr, arr+3);

    cout << first.size() << ' ' << second.size() << ' ' << third.size() << endl;
    // 7 5 3
}
#include <iostream>
#include <deque>

using namespace std;

int main(){
    deque<int> dq;

    for(int i = 1; i <= 5; ++i)
        dq.push_back(i);
    // 1 2 3 4 5
    for(int i = 6; i < 10; ++i)
        dq.push_front(i);
    // 10 9 8 7 6 1 2 3 4 5
    dq.pop_back();
    // 10 9 8 7 6 1 2 3 4
    dq.pop_front();
    // 9 8 7 6 1 2 3 4
}
#include <iostream>
#include <deque>

using namespace std;

int main(){
    deque<int> dq(3, 100);
    dq.insert(dq.begin(), 200);
    dq.insert(dq.begin(), 2, 300);
    // 300 300 200 100 100 100

    deque<int> dq2(2, 400);
    dq.insert(dq.begin() + 2, dq2.begin(), dq2.end());
    // 300 300 400 400 200 100 100 100

    int arr[] = {501, 502, 503};
    dq.insert(dq.begin(), arr, arr+3);
    // 501 502 503 300 300 400 400 200 100 100 100

    dq.erase(dq.begin()+5);
    // 501 502 503 300 300 400 200 100 100 100
    dq.erase(dq.begin()+3, dq.begin()+4);
    // 501 502 503 400 200 100 100 100

    return 0;
}
#include <iostream>
#include <deque>

using namespace std;

int main(){
    deque<int> dq1(3, 100);
    deque<int> dq2(5, 200);
    dq1.swap(dq2);

    deque<int>::iterator it;
    for(it = dq1.begin(); it != dq1.end(); ++it)
        cout << *it << ' ';
    cout << endl;
    for(it = dq2.begin(); it != dq2.end(); ++it)
        cout << *it << ' ';
    cout << endl;
    // 200 200 200 200 200
    // 100 100 100

    dq1.clear();
    dq1.push_back(1);
    for(it = dq1.begin(); it != dq1.end(); ++it)
        cout << *it << ' ';
    // 1

    return 0;
}

할당

  • get_allocator()
반응형

'C++' 카테고리의 다른 글

[C++] string library  (0) 2020.11.27
[C++] cout 부동소수점 다루기  (0) 2020.11.20
[C++] STL - stack  (0) 2020.10.28
[C++] STL - vector  (0) 2020.10.28
[C++] 반복자  (0) 2020.10.27

+ Recent posts