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

tuple<자료형1, 자료형2, ... >


pair는 2개를 묶는다면, tuple은 여러개의 자료형을 묶을 수 있다.


first, second로 접근하는 것이 아닌, get(인덱스번호) 를 이용해서 접근한다.


<tuple> 에 있다.



사용 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <tuple>
 
using namespace std;
 
int main(void)
{
    tuple<intintint> t1;
    printf("%d %d %d\n", get<0>(t1), get<1>(t1), get<2>(t1));
 
    t1 = make_tuple(102030);
    printf("%d %d %d\n", get<0>(t1), get<1>(t1), get<2>(t1));
 
    return 0;
}
cs




다음과 같이 get에 인덱스 번호 대신에 변수를 넣어서 사용할 수 없다.

1
2
3
4
for (int i = 0; i < 3; i++
{
        printf("%d\n", get<i>(t1));
}
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]bitset  (0) 2018.07.04
[STL] C++ STL pair  (0) 2018.06.22

pair<자료형1, 자료형2> 


두 자료형을 묶는다.


첫 번째 자료는 first, 두 번째 자료는 second로 접근


#include <utility> 에 있다.


단독 보다는 <algorithm>, <vector> 등의 헤더와 같이 사용하는데 이 헤더에 이미 include 하고 있어서 따로 include 안해도 된다.



생성 방법 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <algorithm>
 
using namespace std;
 
int main(void)
{
    pair<intint> p1;
    printf("%d %d\n", p1.first, p1.second);
    
    p1 = make_pair(1020);
    printf("%d %d\n", p1.first, p1.second);
 
    p1 = pair<intint>(3040);
    printf("%d %d\n", p1.first, p1.second);
 
    pair<intint> p2(5060);
    printf("%d %d\n", p2.first, p2.second);
 
    return 0;
}
 
 
cs




pair 안에 pair 자료형을 사용할 수도 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <algorithm>
 
using namespace std;
 
int main(void)
{
    pair<pair<intint>pair<int,int>> p1;
    p1 = make_pair(make_pair(1020), make_pair(3040));
    printf("%d %d\n%d %d\n", p1.first.first, p1.first.second, p1.second.first,p1.second.second);
 
    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]bitset  (0) 2018.07.04
[STL] C++ STL tuple  (0) 2018.06.22

+ Recent posts