C++ set


set을 사용하기 위해서는 <set> 헤더를 인클루드 해야한다.


key라 불리는 원소의 집합. key이므로 중복된 값을 가지지 않는다. 중복된 값이 필요하다면 multiset을 이용하면 된다.


set은 균형 이진트리로 구현되어있다.


insert()함수로 데이터를 추가할 수 있으며, 삽입된 데이터는 자동으로 정렬된다. (기본 오름차순)



 생성자

 

 set s

 빈 컨테이너 셋 s 생성

 set s(pred)

 s는 빈 컨테이너 이며, 정렬 기준은 pred 조건자를 사용

 set s(s2)

 셋 s는 셋 s2의 복사본

 set s(b, e)

 셋 s는 반복자 구간 [b, e)로 초기화된 원소를 가짐

 set s(b, e, pred)

 셋 s는 반복자 구간 [b, e)로 초기화된 원소를 가지며, 정렬 기준은 pred 조건자를 사용


생성자 사용 예제

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
#include <iostream>
#include <set>
#include <functional>
int main()
{
    std::set<int> first;                           // empty set of ints
 
    int myints[] = { 10,20,30,40,50 };
    std::set<int> second(myints, myints + 5);        // range
 
    std::set<int> third(second);                  // a copy of second
 
    std::set<int> fourth(second.begin(), second.end());  // iterator ctor.
 
    std::set<intstd::greater<int> > fifth = { 1020304050 };
 
    std::cout << "first : ";
    for (auto it = first.begin(); it != first.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "second : ";
    for (auto it = second.begin(); it != second.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "third : ";
    for (auto it = third.begin(); it != third.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "fourth : ";
    for (auto it = fourth.begin(); it != fourth.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "fifth : ";
    for (auto it = fifth.begin(); it != fifth.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    return 0;
}
 
cs


실행 결과



주요 멤버 함수

insert() 

 셋에 데이터 삽입

 erase()

 셋에서 원소 제거

 find()

 셋에서 원소의 위치 검색

 count()

 셋에서 원소의 개수 검색

 clear()

 셋의 모든 원소 제거


사용예제

insert()

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
#include <iostream>
#include <set>
 
int main()
{
    std::set<int> myset;
    std::set<int>::iterator it;
    std::pair<std::set<int>::iteratorbool> ret;
 
    // set some initial values:
    for (int i = 1; i <= 5++i) myset.insert(i * 10);    // set: 10 20 30 40 50
 
    ret = myset.insert(20);               // no new element inserted
 
    if (ret.second == false) it = ret.first;  // "it" now points to element 20
 
    myset.insert(it, 25);                 // max efficiency inserting
    myset.insert(it, 24);                 // max efficiency inserting
    myset.insert(it, 26);                 // no max efficiency inserting
 
    int myints[] = { 5,10,15 };              // 10 already in set, not inserted
    myset.insert(myints, myints + 3);
 
    std::cout << "myset contains:";
    for (it = myset.begin(); it != myset.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs



erase(), find()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <set>
 
int main()
{
    std::set<int> myset;
    std::set<int>::iterator it;
 
    // set some initial values:
    for (int i = 1; i <= 5; i++) myset.insert(i * 10);    // set: 10 20 30 40 50
 
    //20, 40의 위치를 찾은 후 제거
    it = myset.find(20);
    myset.erase(it);
    myset.erase(myset.find(40));
 
    std::cout << "myset contains:";
    for (it = myset.begin(); it != myset.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs


count()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <set>
 
int main()
{
    std::set<int> myset;
 
    // set some initial values:
    for (int i = 1; i<5++i) myset.insert(i * 3);    // set: 3 6 9 12
 
    for (int i = 0; i<10++i)
    {
        std::cout << i;
        if (myset.count(i) != 0)
            std::cout << " is an element of myset.\n";
        else
            std::cout << " is not an element of myset.\n";
    }
 
    return 0;
}
cs



참조: http://www.cplusplus.com/reference/set/set/

참고문헌: 뇌를 자극하는 C++ STL

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL map  (0) 2018.07.22
[STL] C++ STL multiset  (0) 2018.07.22
[STL] C++ STL string to int/float/double/long long  (0) 2018.07.19
[STL] C++ STL list  (0) 2018.07.19
[STL] C++ STL deque  (0) 2018.07.19

C++ string


string 문자열에 숫자가 들어 있을 때, 이를 int/float/double/long long 등으로 변환할 수 있다.



 종류

 

 stoi

 int

 stoul

 unsigned long

 stoull

 unsigned long long

 stof

 float

 stod

 double

 stold

 long double



사용 예제

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
#include <iostream>
#include <string>
 
int main()
{
    std::string str_dec = "2001, A Space Odyssey";
    std::string str_hex = "40c3";
    std::string str_bin = "-10010110001";
    std::string str_auto = "0x7f";
    std::string str_auto2 = "077";
    std::string str_auto3 = "77.5";
    
 
    int i_dec = std::stoi(str_dec);//string의 앞쪽 정수만 int형으로 변환
    int i_hex = std::stoi(str_hex, nullptr, 16); //string 16진수를 10진수로
    int i_bin = std::stoi(str_bin, nullptr, 2);//string 2진수를 10진수로
    int i_auto = std::stoi(str_auto, nullptr, 0);//알아서 변환 string 16진수를 10진수로
    int i_auto2 = std::stoi(str_auto2, nullptr, 0);//string 8진수를 10진수로
    int i_auto3 = std::stoi(str_auto3, nullptr, 0);//string 10진수를 10진수로
 
    std::cout << str_dec << ": " << i_dec << "\n";
    std::cout << str_hex << ": " << i_hex << '\n';
    std::cout << str_bin << ": " << i_bin << '\n';
    std::cout << str_auto << ": " << i_auto << '\n';
    std::cout << str_auto2 << ": " << i_auto2 << '\n';
    std::cout << str_auto3 << ": " << i_auto3 << '\n';
 
    return 0;
}
 
cs


실행 결과


마찬가지로 int/double/flaot 등을 string 으로 변환할 수 있다.


사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
 
int main()
{
    std::string str1;
    std::string str2;
    std::string str3;
    
    int n1 = 100;
    double d1 = 200.5;
    long long n2 = 123456789123456789;
 
    str1 = std::to_string(n1);
    str2 = std::to_string(d1);
    str3 = std::to_string(n2);
 
    std::cout << str1 << "\n";
    std::cout << str2 << "\n";
    std::cout << str3 << "\n";
 
    return 0;
}
 
cs



참조: http://www.cplusplus.com/reference/string/

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL multiset  (0) 2018.07.22
[STL] C++ STL set  (0) 2018.07.22
[STL] C++ STL list  (0) 2018.07.19
[STL] C++ STL deque  (0) 2018.07.19
[STL] C++ STL vector  (0) 2018.07.19

C++ list


STL list는 이중 연결 리스트 방식으로 구현되어있다.



 생성자

 

 list li

 빈 컨테이너 리스느 li 생성

 list li(n)

 리스트 li는 기본값으로 초기화된 n개의 원소를 가짐

 list li(n, x)

 리스트 li는 x로 초기화된 n개의 원소를 가짐

 list li(li2)

 리스트 li는 li2의 복사본

 list li(b, e)

 리스트 li는 반복자 구간 [b, e)로 초기화된 원소를 가짐



생성자 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <list>
using namespace std;
 
int main(void)
{
    list<int> v1; //길이 = 0
    list<int> v2(100); //길이 = 100
    list<int> v3(1005); //길이 = 100, 5로 초기화
    list<int> v4 = { 12345 }; //길이 5
 
    cout << "v1 크기 : " << v1.size() << '\n';
    cout << "v2 크기 : " << v2.size() << '\n';
    cout << "v3 크기 : " << v3.size() << '\n';
    cout << "v4 크기 : " << v4.size() << '\n';
 
    return 0;
}
cs


주요 멤버 함수

 empty()

 리스트가 비어있는가?

 size()

 리스트의 크기 반환

 front()

 리스트의 첫번째 원소에 접근

 back()

 리스트의 마지막 원소에 접근

 push_front()

 리스트의 가장 앞에 데이터 추가

 pop_front()

 리스트의 첫 데이터 제거

 push_back()

 리스트의 가장 뒤에 데이터 추가

 pop_back()

 리스트의 마지막 데이터 제거

 insert()

 리스트의 특정 위치에 데이터 삽입

 erase()

 리스트의 특정 구간 데이터 제거


사용 예제

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
#include <iostream>
#include <list>
 
int main()
{
    std::list<int> mylist;
    std::list<int>::iterator it1;
    int sum(0);
 
    mylist.push_back(300); //300
    mylist.push_back(400); //300 400
    mylist.push_back(500); //300 400 500
    mylist.push_front(200); //200 300 400 500
    mylist.push_front(100); //100 200 300 400 500
 
    while (!mylist.empty())
    {
        sum += mylist.front();
        mylist.pop_front();
    }
 
    std::cout << "The elements of mylist add up to " << sum << '\n';
 
    // set some values:
    for (int i = 1; i<10++i) mylist.push_back(i * 10);
 
                                // 10 20 30 40 50 60 70 80 90
    it1 = mylist.begin();        // ^^
    ++it1;                      //    ^              
 
    it1 = mylist.erase(it1);   // 10 30 40 50 60 70 80 90
                               //    ^  
 
    std::cout << "mylist contains:";
    for (it1 = mylist.begin(); it1 != mylist.end(); ++it1)
        std::cout << ' ' << *it1;
    std::cout << '\n';
 
    //resize
    mylist.resize(2); //10 30
    std::cout << "my list size : " << mylist.size() << '\n';
 
    //clear
    mylist.clear(); //
    std::cout << "my list size : " << mylist.size() << '\n';
 
    for (int i = 1; i <= 10; i++) mylist.push_back(i);//1 2 3 4 5 6 7 8 9 10
 
    std::list<int>::iterator it = mylist.begin();
    ++it;
 
    it = mylist.insert(it, 20); //1 20 2 3 4 5 6 7 8 9 10
 
    mylist.insert(it, 230); //1 30 30 20 2 3 4 5 6 7 8 9 10
 
    std::cout << "mylist contains:";
    for (it = mylist.begin(); it != mylist.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
 
cs


참조: http://www.cplusplus.com/reference/list/list/

참고문헌: 뇌를 자극하는 C++ STL

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL set  (0) 2018.07.22
[STL] C++ STL string to int/float/double/long long  (0) 2018.07.19
[STL] C++ STL deque  (0) 2018.07.19
[STL] C++ STL vector  (0) 2018.07.19
[STL] C++ STL string  (0) 2018.07.19

c++ deque


deque를 사용하기 위해서는 <deque> 헤더를 인클루드 해야한다.


deque는 큐형태로, 양방향으로 자료를 넣고 뺄 수 있다.



 생성자

 

 deque dq

 빈 컨테이더 덱 dq 생성

 deque dq(n)

 덱 dq는 기본값으로 초기화된 n개의 원소를 가짐

 deque dq(n, x)

 덱 dq는 x로 초기화된 n개의 원소를 가짐

 deque dq(dq2)

 덱 dq는 덱 dq2의 복사본

 deque dq(b, e)

 덱 dq는 반복자 구간 [b, e)로 초기화된 원소를 가짐


생성자 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <deque>
using namespace std;
 
int main(void)
{
    deque<int> v1; //길이 = 0
    deque<int> v2(100); //길이 = 100
    deque<int> v3(1005); //길이 = 100, 5로 초기화
    deque<int> v4 = { 12345 }; //길이 5
 
    cout << "v1 크기 : " << v1.size() << '\n';
    cout << "v2 크기 : " << v2.size() << '\n';
    cout << "v3 크기 : " << v3.size() << '\n';
    cout << "v4 크기 : " << v4.size() << '\n';
 
    return 0;
}
cs


주요 멤버 함수

 push_back()

 덱의 가장 뒤에 데이터 추가

 push_front()

 덱의 가장 앞에 데이터 추가

 pop_back()

 덱의 마지막 데이터 제거

 pop_front()

 덱의 첫 데이터 제거

 clear()

 덱의 모든 데이터 제거

 size()

 덱의 크기

 insert()

 덱의 특정 위치에 데이터 삽입

 erase()

 덱의 특정 구간 데이터 제거


사용 예제

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
#include <iostream>
#include <deque>
 
int main()
{
    std::deque<int> mydeque;
    int sum(0);
 
    mydeque.push_back(300); //300
    mydeque.push_back(400); //300 400
    mydeque.push_back(500); //300 400 500
    mydeque.push_front(200); //200 300 400 500
    mydeque.push_front(100); //100 200 300 400 500
 
    while (!mydeque.empty())
    {
        sum += mydeque.back();
        mydeque.pop_back();
    }
 
    std::cout << "The elements of mydeque add up to " << sum << '\n';
 
    // deque is empty
    for (int i = 1; i <= 10; i++) mydeque.push_back(i);//1 2 3 4 5 6 7 8 9 10
 
    // erase the 6th element
    mydeque.erase(mydeque.begin() + 5);//1 2 3 4 5 7 8 9 10
 
    // erase the first 3 elements:
    mydeque.erase(mydeque.begin(), mydeque.begin() + 3);//4 5 7 8 9 10
 
    std::cout << "mydeque contains:";
    for (unsigned i = 0; i<mydeque.size(); ++i)
        std::cout << ' ' << mydeque[i];
    std::cout << '\n';
 
    //resize
    mydeque.resize(2); //4 5
    std::cout << "my deque size : " << mydeque.size() << '\n';
 
    //clear
    mydeque.clear(); //
    std::cout << "my deque size : " << mydeque.size() << '\n';
 
    for (int i = 1; i <= 10; i++) mydeque.push_back(i);//1 2 3 4 5 6 7 8 9 10
 
    std::deque<int>::iterator it = mydeque.begin();
    ++it;
 
    it = mydeque.insert(it, 20); //1 20 2 3 4 5 6 7 8 9 10
 
    mydeque.insert(it, 230); //1 30 30 20 2 3 4 5 6 7 8 9 10
 
    std::cout << "mydeque contains:";
    for (it = mydeque.begin(); it != mydeque.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
 
cs



참조: http://www.cplusplus.com/reference/deque/deque/

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL string to int/float/double/long long  (0) 2018.07.19
[STL] C++ STL list  (0) 2018.07.19
[STL] C++ STL vector  (0) 2018.07.19
[STL] C++ STL string  (0) 2018.07.19
[STL]C++ STL priority_queue  (0) 2018.07.19

C++ vector


vector를 사용하기 위해서는 <vector> 헤더를 인클루드 해야한다.


vector는 배열 기반 컨테이너로, 길이를 변경할 수 있는 배열이라고 생각하면 이해하기 쉽다.


 생성자

 

 vector v

 빈 컨테이너 벡터 v 생성

 vector v(n)

 벡터 v는 기본값으로 초기화된 n개의 원소를 가짐

 vector v(n, x)

 벡터 v는 x로 초기화된 n개의 원소를 가짐

 vector v(v2)

 벡터 v는 벡터 v2의 복사본

 vector v(b, e)

 벡터 v는 반복자 구간 [b, e)로 초기화된 원소를 가짐


생성자 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>
using namespace std;
 
int main(void)
{
    vector<int> v1; //길이 = 0
    vector<int> v2(100); //길이 = 100
    vector<int> v3(1005); //길이 = 100, 5로 초기화
    vector<int> v4 = { 12345 }; //길이 5
 
    cout << "v1 크기 : " << v1.size() << '\n';
    cout << "v2 크기 : " << v2.size() << '\n';
    cout << "v3 크기 : " << v3.size() << '\n';
    cout << "v4 크기 : " << v4.size() << '\n';
 
    return 0;
}
cs



자료형으로 pair, tuple 등도 사용할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int main(void)
{
    vector<pair<intint>> v1 = { {10,20}, {30,40} };
    vector<pair<intint>> v2 = { make_pair(10,20) };
 
    printf("v1 크기 : %d\n", v1.size());
    printf("v2 크기 : %d\n", v2.size());
    
    return 0;
}
 
cs


vector는 배열처럼 임의 접근이 가능하다. ex) v[13] = 12 //벡터의 13번째를 12로 할당


멤버 함수

 push_back()

 벡터의 가장 뒤에 데이터 추가

 pop_back()

 벡터의 마지막 데이터 제거

 clear()

 벡터의 모든 데이터 제거

 resize()

 벡터 크기 변경, 크기보다 뒤에 있는 데이터는 제거

 size()

 벡터의 크기

 erase()

 벡터의 해당 구간 데이터 제거


사용 예제

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
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> myvector;
    int sum(0);
    myvector.push_back(100);
    myvector.push_back(200);
    myvector.push_back(300);
 
    while (!myvector.empty())
    {
        sum += myvector.back();
        myvector.pop_back();
    }
 
    std::cout << "The elements of myvector add up to " << sum << '\n';
 
    // vector is empty
    for (int i = 1; i <= 10; i++) myvector.push_back(i);
 
    // erase the 6th element
    myvector.erase(myvector.begin() + 5);
 
    // erase the first 3 elements:
    myvector.erase(myvector.begin(), myvector.begin() + 3);
 
    std::cout << "myvector contains:";
    for (unsigned i = 0; i<myvector.size(); ++i)
        std::cout << ' ' << myvector[i];
    std::cout << '\n';
 
    //resize
    myvector.resize(2);
    std::cout << "my vector size : " << myvector.size() << '\n';
 
    //clear
    myvector.clear();
    std::cout << "my vector size : " << myvector.size() << '\n';
    return 0;
}
cs


실행 결과



참조: http://www.cplusplus.com/reference/vector/vector/

참고문헌: 뇌를 자극하는 C++ STL

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL list  (0) 2018.07.19
[STL] C++ STL deque  (0) 2018.07.19
[STL] C++ STL string  (0) 2018.07.19
[STL]C++ STL priority_queue  (0) 2018.07.19
[STL]C++ STL queue  (0) 2018.07.19

C++ string


string는 C++ 표준 라이브러리로 STL에 포함되지 않는다.


string는 문자만을 원소로 저장하고 문자열을 조작할 목적으로 사용되는 컨테이너이다.


string를 사용하기 위해서는 <stirng> 헤더를 인클루드 해야한다.


C/C++ 문자열처럼 마지막에 '\0'을 포함해야하는 요구사항은 없다.



 생성자

 

 string s

 기본 생성자로 s 생성

 string s(str)

 str 문자열로 s 생성

 string s(str, n)

 str 문자열에서 n개의 문자로 s를 생성

 string s(n, c)

 n개의 c문자로 s를 생성

 string s(iter1, iter2)

 반복자 구간 [iter1, iter2)의 문자로 s를 생성

 string s(p1, p2)

 포인터 구간 [p1, p2)의 문자로 s를 생성


생성자 사용 예제

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
#include <iostream> 
#include <string>
 
int main()
{
    std::string t("Hello!");
    const char* p1 = "Hello!";
    const char* p2 = p1 + 6;
 
    std::string s1;
    std::string s2("Hello!");
    std::string s3("Hello!"5);
    std::string s4(5'H');
    std::string s5(t.begin(), t.end());
    std::string s6(p1, p2);
 
    std::cout << "s1()\t\t: " << s1 << '\n';
    std::cout << "s2(str)\t\t: " << s2 << '\n';
    std::cout << "s3(str, n)\t: " << s3 << '\n';
    std::cout << "s4(n, c)\t: " << s4 << '\n';
    std::cout << "s5(iter1, iter2): " << s5 << '\n';
    std::cout << "s6(p1, p2)\t: " << s6 << '\n';
 
    return 0;
}
 
cs


생성자 예제 실행 결과



멤버함수

append(), +=, push_back() 사용 예제

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
#include <iostream> 
#include <string>
 
int main()
{
    std::string s1("Hello");
    std::string s2("Hello");
    std::string s3("Hello");
    std::string s4("Hello");
    std::string s5("Hello");
    std::string s6("Hello");
    std::string s7("Hello");
    std::string s8("Hello");
    std::string s9("Hello");
    std::string s10("Hello");
    
    std::string t(" string!");
    const char* p1 = " string!";
    const char* p2 = p1 + 8;
 
    s1.append(t);//s1 + t
    s2.append(t, 04);//s2 + (t문자열에서 0부터 4번째 인덱스 까지 추가)
    s3.append(" string!");
    s4.append(" string!"5);//주어진 문자열에서 5개 문자 추가
    s5.append(t.begin(), t.end());
    s6.append(p1, p2);
    s7.append(5's');//주어진 문자 c를 n번 추가
    s8 += t;
    s9 += " string!";
 
    for (std::string::iterator it = t.begin(); it != t.end(); it++)
        s10.push_back((*it));
 
    std::cout << "s1.append(s)\t\t:" << s1 << '\n';
    std::cout << "s2.append(s, off, n)\t:" << s2 << '\n';
    std::cout << "s3.append(str)\t\t:" << s3 << '\n';
    std::cout << "s4.append(str, n)\t:" << s4 << '\n';
    std::cout << "s5.append(iter1, iter2)\t:" << s5 << '\n';
    std::cout << "s6.append(p1, p2)\t:" << s6 << '\n';
    std::cout << "s7.append(n, c)\t\t:" << s7 << '\n';
    std::cout << "s8+=s\t\t\t:" << s8 << '\n';
    std::cout << "s9+=str\t\t\t:" << s9 << '\n';
    std::cout << "s10.push_back(c)\t:" << s10 << '\n';
 
    return 0;
}
 
cs


실행 결과



멤버함수

append(), = 사용 예제

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
#include <iostream> 
#include <string>
 
int main()
{
    std::string s1;
    std::string s2;
    std::string s3;
    std::string s4;
    std::string s5;
    std::string s6;
    std::string s7;
    std::string s8;
    std::string s9;
        
    std::string t("Hello string!");
    const char* p1 = "Hello string!";
    const char* p2 = p1 + 13;
 
    s1.assign(t);//s1 + t
    s2.assign(t, 05);//s2 + (t문자열에서 0부터 5번째 인덱스 까지 할당)
    s3.assign("Hello");
    s4.assign("Hello!"5);//주어진 문자열에서 5개 문자 추가
    s5.assign(t.begin(), t.end());
    s6.assign(p1, p2);
    s7.assign(5'H');//주어진 문자 c를 n번 추가
    s8 = t;
    s9 = "Hello string!";
    
    std::cout << "s1.append(s)\t\t:" << s1 << '\n';
    std::cout << "s2.append(s, off, n)\t:" << s2 << '\n';
    std::cout << "s3.append(str)\t\t:" << s3 << '\n';
    std::cout << "s4.append(str, n)\t:" << s4 << '\n';
    std::cout << "s5.append(iter1, iter2)\t:" << s5 << '\n';
    std::cout << "s6.append(p1, p2)\t:" << s6 << '\n';
    std::cout << "s7.append(n, c)\t\t:" << s7 << '\n';
    std::cout << "s8+=s\t\t\t:" << s8 << '\n';
    std::cout << "s9+=str\t\t\t:" << s9 << '\n';
 
    return 0;
}
 
cs


assign(), = 사용 예제는 append(), +=과 똑같다고 보면 된다.

실행 결과



멤버 함수

c_str(), data() 사용 예제


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream> 
#include <string>
 
int main()
{
    std::string s("Hello!");
    const char *str;
    const char *buf;
 
    str = s.c_str();
    buf = s.data();
 
    std::cout << "'\\0' 문자로 끝나는 문자열: " << str << '\n';
    std::cout << "'\\0' 문자를 포함하지 않는 문자열 배열: ";
    for (int i = 0; i < s.size(); i++)
        std::cout << buf[i];
    std::cout << '\n';
 
    return 0;
}
 
cs


실행 결과


scanf/printf를 사용할 때, c_str()을 사용하면 string 문자열을 출력할 수 있다.



멤버 함수

문자열 비교 compare() 사용 예제

s1 > s2 : 1

s1 < s2 : -1

s1 == s2 : 0


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream> 
#include <string>
 
int main()
{
    std::string s1("ABCDEF");
    std::string s2("CBAABC");
    const char* s3 = "CBAABC";
 
    std::cout << "s1.compare(s2) : " << s1.compare(s2) << '\n'// ABCDEF < CBAABC
    std::cout << "s1.compare(off, n, s2) : " << s1.compare(33, s2) << '\n'//ABCDEF > ABC
    std::cout << "s1.compare(off1, n1, s1, off2, n2) : " << s1.compare(03, s2, 33<< '\n'// ABC == ABC
    std::cout << "s1.compare(s3) : " << s1.compare(s3) << '\n'// ABCDEF < CBAABC
    std::cout << "s1.compare(off, n, s3) : " << s1.compare(33, s3) << '\n'//ABCDEF > ABC
    std::cout << "s1.compare(off1, n1, s3, n2) : " << s1.compare(21, s3, 1<< '\n'//C == C
 
    return 0;
}
 
cs


실행 결과


문자열 비교 연산(!=, ==, >, <, >=, <=)는 전체 문자열을 비교하지만 compare()는 부분 문자열을 비교할 수 있는 장점이 있다.


멤버 함수

copy() 

문자열 복사가 가능하다. copy()는 마지막에 '\0'을 추가하지 않으므로 별도로 넣어줘야 한다.

부분 복사도 가능하다.


사용 예제

1
2
3
4
5
s.copy(buf, s.length());
buf[s.length()] = '\-';
 
s.copy(buf, 42);//복사할 위치, 개수, 오프셋
buf[4= '0';
cs


멤버 함수 

find()

문자열에서 해당 문자/문자열의 위치를 반환. 없을 경우 -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
30
31
#include <iostream>       
#include <string>        
 
int main()
{
    std::string str("There are two needles in this haystack with needles.");
    std::string str2("needle");
 
    // different member versions of find in the same order as above:
    std::size_t found = str.find(str2);
    if (found != std::string::npos)
        std::cout << "first 'needle' found at: " << found << '\n';
 
    found = str.find("needles are small", found + 16);
    if (found != std::string::npos)
        std::cout << "second 'needle' found at: " << found << '\n';
 
    found = str.find("haystack");
    if (found != std::string::npos)
        std::cout << "'haystack' also found at: " << found << '\n';
 
    found = str.find('.');
    if (found != std::string::npos)
        std::cout << "Period found at: " << found << '\n';
 
    // let's replace the first needle:
    str.replace(str.find(str2), str2.length(), "preposition");
    std::cout << str << '\n';
 
    return 0;
}
cs


멤버 함수

insert()

문자열에서 원하는 위치에 원하는 문자열 추가


사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
 
int main()
{
    std::string str = "to be question";
    std::string str2 = "the ";
    std::string str3 = "or not to be";
    std::string::iterator it;
 
    // used in the same order as described above:
    str.insert(6, str2);                 // to be (the )question
    str.insert(6, str3, 34);             // to be (not )the question
    str.insert(10"that is cool"8);    // to be not (that is )the question
    str.insert(10"to be ");            // to be not (to be )that is the question
    str.insert(151':');               // to be not to be(:) that is the question
    it = str.insert(str.begin() + 5','); // to be(,) not to be: that is the question
    str.insert(str.end(), 3'.');       // to be, not to be: that is the question(...)
    str.insert(it + 2, str3.begin(), str3.begin() + 3); // (or )
 
    std::cout << str << '\n';
    return 0;
}
cs


멤버 함수

replace()

원하는 위치의 문자열을 교체


사용 예제

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
#include <iostream>
#include <string>
 
int main()
{
    std::string base = "this is a test string.";
    std::string str2 = "n example";
    std::string str3 = "sample phrase";
    std::string str4 = "useful.";
 
    // replace signatures used in the same order as described above:
 
    // Using positions:                 0123456789*123456789*12345
    std::string str = base;           // "this is a test string."
    str.replace(95, str2);          // "this is an example string." (1)
    str.replace(196, str3, 76);     // "this is an example phrase." (2)
    str.replace(810"just a");     // "this is just a phrase."     (3)
    str.replace(86"a shorty"7);  // "this is a short phrase."    (4)
    str.replace(2213'!');        // "this is a short phrase!!!"  (5)
 
                                       // Using iterators:                                               0123456789*123456789*
    str.replace(str.begin(), str.end() - 3, str3);                    // "sample phrase!!!"      (1)
    str.replace(str.begin(), str.begin() + 6"replace");             // "replace phrase!!!"     (3)
    str.replace(str.begin() + 8, str.begin() + 14"is coolness"7);    // "replace is cool!!!"    (4)
    str.replace(str.begin() + 12, str.end() - 44'o');                // "replace is cooool!!!"  (5)
    str.replace(str.begin() + 11, str.end(), str4.begin(), str4.end());// "replace is useful."    (6)
    std::cout << str << '\n';
    return 0;
}
cs


멤버 함수

substr()

문자열의 부분 문자열을 구하는 함수


사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
 
int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)
 
  std::string str2 = str.substr (3,5);     // "think"
 
  std::size_t pos = str.find("live");      // position of "live" in str
 
  std::string str3 = str.substr (pos);     // get from "live" to the end
 
  std::cout << str2 << ' ' << str3 << '\n';
 
  return 0;
}
cs


멤버 함수

erase()

문자열을 지우는 함수


사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
 
int main ()
{
  std::string str ("This is an example sentence.");
  std::cout << str << '\n';
                                           // "This is an example sentence."
  str.erase (10,8);                        //            ^^^^^^^^
  std::cout << str << '\n';
                                           // "This is an sentence."
  str.erase (str.begin()+9);               //           ^
  std::cout << str << '\n';
                                           // "This is a sentence."
  str.erase (str.begin()+5, str.end()-9);  //       ^^^^^
  std::cout << str << '\n';
                                           // "This sentence."
  return 0;
}
cs


참조: http://www.cplusplus.com/reference/string/string/

참고 문헌: 뇌를 자극하는 C++ STL

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL deque  (0) 2018.07.19
[STL] C++ STL vector  (0) 2018.07.19
[STL]C++ STL priority_queue  (0) 2018.07.19
[STL]C++ STL queue  (0) 2018.07.19
[STL]C++ STL stack  (0) 2018.07.19

C++ priority_queue


우선순위 큐를 구현한 컨테이너이다.


priority_queue를 사용하기 위해서는 <queue> 헤더를 인클루드 해야한다.


vector<>컨테이너를 기반으로 구현되어 있으며, deque컨테이너도 사용할 수 있다. 기본 정렬은 less 방식(내림차순)이다.


 멤버 함수

 

 empty()

 큐에 원소가 없는가?

 size()

 큐에 원소가 몇개 있는가?

 top()

 큐에서 가장 우선순위가 높은 원소는?

 push()

 큐에 원소를 추가

 pop()

 큐에서 원소를 제거



사용 예제

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
#include <iostream>       
#include <queue>    
#include <functional>
 
int main()
{
    std::priority_queue<int> mypq1;
    mypq1.push(30);
    mypq1.push(10);
    mypq1.push(50);
    mypq1.push(40);
    mypq1.push(20);
 
    std::cout << "priority_queue [less] :\n";
    while (!mypq1.empty())
    {
        std::cout << mypq1.top() << '\n';
        mypq1.pop();
    }
    std::cout << "========================\n";
 
 
    std::priority_queue<intstd::vector<int>std::greater<int> > mypq2;
    mypq2.push(30);
    mypq2.push(10);
    mypq2.push(50);
    mypq2.push(40);
    mypq2.push(20);
 
    std::cout << "priority_queue [greater] :\n";
    while (!mypq2.empty())
    {
        std::cout << mypq2.top() << '\n';
        mypq2.pop();
    }
    std::cout << "========================\n";
 
    return 0;
}
 
cs

실행 결과


참조: http://www.cplusplus.com/reference/queue/priority_queue/

참고문헌: 뇌를 자극하는 C++ STL


'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL vector  (0) 2018.07.19
[STL] C++ STL string  (0) 2018.07.19
[STL]C++ STL queue  (0) 2018.07.19
[STL]C++ STL stack  (0) 2018.07.19
[STL]bitset  (0) 2018.07.04

C++ queue


FIFO(First-In First-Out) 방식의 컨테이너


queue를 사용하기 위해서는 <queue> 헤더를 인클루드 해야한다.




 멤버 함수

 

 empty()

 큐에 원소가 없는가?

 size()

 큐에 원소가 몇개 있는가?

 front()

 큐에서 가장 앞에 있는 원소는?

 back()

 큐에서 가장 뒤에 있는 원소는?

 push()

 큐에 원소를 추가

 pop()

 큐에 원소를 제거


사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>       
#include <queue>          
 
int main()
{
    std::queue<int> myqueue;
    int sum(0);
 
    for (int i = 1; i <= 10; i++) myqueue.push(i);
 
    std::cout << "queue front : " << myqueue.front() << '\n';
    std::cout << "queue back : " << myqueue.back() << '\n';
 
    while (!myqueue.empty())
    {
        sum += myqueue.front();
        myqueue.pop();
    }
 
    std::cout << "total: " << sum << '\n';
 
    return 0;
}
cs


스택과 마찬가지로 front/back을 사용하여 큐의 원소에 접근한다고해서 원소가 pop되는 것은 아니기 때문에, 별도로 pop 함수를 호출해야한다.


실행 결과



참조: http://www.cplusplus.com/reference/queue/queue/

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL string  (0) 2018.07.19
[STL]C++ STL priority_queue  (0) 2018.07.19
[STL]C++ STL stack  (0) 2018.07.19
[STL]bitset  (0) 2018.07.04
[STL] C++ STL tuple  (0) 2018.06.22

C++ stack


LIFO(Last-In First-Out) 방식의 컨테이너


stack을 사용하기 위해서는 <stack> 헤더를 인클루드 해야한다.




 멤버함수 

 

 empty()

 스택에 원소가 없는가?

 size()

 스택에 원소가 몇개 있는가?

 top()

 스택의 다음 원소는?(가장 상단의 원소는)

 push()

 스택에 원소를 추가

 pop()

 스택에 원소를 제거



사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream> 
#include <stack>
 
int main()
{
    std::stack<int> mystack;
    int sum(0);
 
    for (int i = 1; i <= 10; i++) mystack.push(i);
 
    while (!mystack.empty())
    {
        sum += mystack.top();
        mystack.pop();
    }
 
    std::cout << "total: " << sum << '\n';
 
    return 0;
}
cs


주의할 점은 top()으로 스택의 상단의 원소를 사용할 때, 원소가 제거되지 않기 때문에 pop()을 사용하여 별도로 제거 과정을 수행해야 한다.


실행 결과



참조: http://www.cplusplus.com/reference/stack/stack/

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL]C++ STL priority_queue  (0) 2018.07.19
[STL]C++ STL queue  (0) 2018.07.19
[STL]bitset  (0) 2018.07.04
[STL] C++ STL tuple  (0) 2018.06.22
[STL] C++ STL pair  (0) 2018.06.22

Bitset

레퍼런스


비트를 다루는 STL


#include <bitset> 을 이용


bitset<비트개수> 변수명

bitset<비트개수> 변수명(초기값) 으로 bitset 선언. 초기값으로는 int, float, double, string 가능하다.

ex)

1
2
bitset<8> b(100);
bitset<8> b("100"); //이진수 100
cs

 

비트셋은 배열처럼 인덱스로 접근 가능 (위 비트셋 100에서  b[0] = 0, b[1] = 0, b[2] = 1)


멤버함수

test(인덱스): 인덱스의 비트가 1이면 true, 0이면 false 반환

set(): 전체 비트를 1로 설정

set(인덱스): 해당 인덱스의 비트를 1로 설정

set(인덱스, 비트): 해당 인덱스의 비트를 지정한 비트로 설정

reset(): 전체 비트를 0으로 설정

reset(인덱스): 해당 인덱스의 비트를 0으로 설정

flip(): 전체 비트를 반전( 0은 1로, 1은 0으로)

flip(인덱스): 해당 인덱스의 비트를 반전

all(): 모든 비트가 1인지 검사

any(): 비트 중 1이 1개 이상 있는지 검사

none(): 모든 비트가 0인지 검사

count(): 비트 중 1의 개수 

size(): 비트셋의 크기 반환

(size() - count() : 비트 중 0의 개수)

to_string(): 전체 비트를 string으로 변환

to_ulong(): 전체 비트를 unsigned long으로 변환

to_ullong(): 전체 비트를 unsigned long long으로 변환



선언 예제 코드

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
#include <bitset>
#include <string>
#include <iostream>
using namespace std;
 
int main(void) {
    
    bitset<8> b1;
    bitset<8> b2;
    bitset<8> b3;
    bitset<8> b4;
    int i1 = 100;
    float f1 = 21;
    double d1 = 11;
    string s1 = "11001";
 
    b1 = bitset<8>(i1); //0110 0100
    b2 = bitset<8>(f1); //0001 0101
    b3 = bitset<8>(d1); //0000 1011
    b4 = bitset<8>(s1); //0001 1001
 
    cout << b1 << '\n';
    cout << b2 << '\n';
    cout << b3 << '\n';
    cout << b4 << '\n';
 
    return 0;
}
cs



'컴퓨터공학 > STL' 카테고리의 다른 글

[STL]C++ STL priority_queue  (0) 2018.07.19
[STL]C++ STL queue  (0) 2018.07.19
[STL]C++ STL stack  (0) 2018.07.19
[STL] C++ STL tuple  (0) 2018.06.22
[STL] C++ STL pair  (0) 2018.06.22

+ Recent posts