C++ algorithm


기타 algorithm에 속한 다른 함수들을 알아본다.


1. sort(begin, end)

구간 [begin, end)를 오름차순 기준으로 정렬한다


sort 사용 예제

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
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector
#include <functional>
 
bool myfunction(int i, int j) { return (i>j); }
 
struct myclass {
    bool operator() (int i, int j) { return (i<j); }
} myobject;
 
int main() {
    int myints[] = { 32,71,12,45,26,80,53,33 };
    std::vector<int> myvector(myints, myints + 8);               // 32 71 12 45 26 80 53 33
 
                                                                 // using default comparison (operator <):
    std::sort(myvector.begin(), myvector.end());               //(12 26 32 33 45 53 71 80)
    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
 
                                                                 // using function as comp
    std::sort(myvector.begin(), myvector.end(), myfunction);     // (80 71 53 45 33 32 26 12)
    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
                                                                 // using object as comp
    std::sort(myvector.begin(), myvector.end(), myobject);       //(12 26 32 33 45 53 71 80)
 
                                                               // print out content:
    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
                                                                        // using function as greater
    std::sort(myvector.begin(), myvector.end(), std::greater<int>());    // (80 71 53 45 33 32 26 12)
    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs



기본은 오름차순 정렬이며

내림차순으로 정렬하기 위햇서는 비교 함수를 구현하거나

<functional> 헤더를 추가하여 41번째 줄과 같이 std::greater<int>() 를 이용해서 비교하면 내림차순으로 정렬할 수 있다.


2. stable_sort(begin, end)

sort와 마찬가지로 정렬하는 함수이다. 차이점은 비교하여 같은 값을 가진 때, 원래 앞에 있던 값이 그대로 앞에 위치하게 된다. 아래 예제를 보자.


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
#include <iostream>     // std::cout
#include <algorithm>    // std::stable_sort
#include <vector>       // std::vector
 
bool compare_as_ints(double i, double j)
{
    return (int(i)<int(j));
}
 
int main() {
    double mydoubles[] = { 3.141.412.724.671.731.321.622.58 };
 
    std::vector<double> myvector;
 
    myvector.assign(mydoubles, mydoubles + 8);
 
    std::cout << "using default comparison:";
    std::stable_sort(myvector.begin(), myvector.end());
    for (std::vector<double>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    myvector.assign(mydoubles, mydoubles + 8);
 
    std::cout << "using 'compare_as_ints' :";
    std::stable_sort(myvector.begin(), myvector.end(), compare_as_ints);
    for (std::vector<double>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs


위 예제에서 비교 연산자없이 stable_sort를 호출하면, 오름차순으로 정렬된다.

하지만 비교 조건으로 int로 변환했을 때(정수부의 값이)를 기준으로 오름차순 정렬하도록 조건을 주었다.

이런 경우 1.41 1.73 1.32 1.62가 모두 1의 값을 가지게 되는데, 이럴 때, 원래 가지고 있던 순서 그대로 위치하게 된다.



3. binary_search(begin, end, value)

정렬된 구간 [begin, end)에서 이진 탐색으로 value를 찾으면 true반환, 못찾으면 false를 반환한다.

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>     // std::cout
#include <algorithm>    // std::binary_search, std::sort
#include <vector>       // std::vector
 
bool myfunction(int i, int j) { return (i<j); }
 
int main() {
    int myints[] = { 1,2,3,4,5,4,3,2,1 };
    std::vector<int> v(myints, myints + 9);                         // 1 2 3 4 5 4 3 2 1
 
                                                                    // using default comparison:
    std::sort(v.begin(), v.end());
 
    std::cout << "looking for a 3... ";
    if (std::binary_search(v.begin(), v.end(), 3))
        std::cout << "found!\n"else std::cout << "not found.\n";
 
    // using myfunction as comp:
    std::sort(v.begin(), v.end(), myfunction);
 
    std::cout << "looking for a 6... ";
    if (std::binary_search(v.begin(), v.end(), 6, myfunction))
        std::cout << "found!\n"else std::cout << "not found.\n";
 
    return 0;
}
cs



4. lower_bound(begin, end, value) 

구간 [begin, end)에서 value보다 작지 않은 첫 번째 이터레이터 반환


5. upper_bound(begin, end, value)

구간 [begin, end)에서 value보다 큰 첫 번째 이터레이터 반환


사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>     // std::cout
#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort
#include <vector>       // std::vector
 
int main() {
    int myints[] = { 10,20,30,30,20,10,10,20 };
    std::vector<int> v(myints, myints + 8);           // 10 20 30 30 20 10 10 20
 
    std::sort(v.begin(), v.end());                // 10 10 10 20 20 20 30 30
 
    std::vector<int>::iterator low, up;
    low = std::lower_bound(v.begin(), v.end(), 20); //          ^
    up = std::upper_bound(v.begin(), v.end(), 20); //                   ^
 
    std::cout << "lower_bound at position " << (low - v.begin()) << '\n';
    std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
 
    return 0;
}
cs



6. next_permutation(begin, end)

구간 [begin, end)를 순열로 보았을 때, 사전 순으로 다음에 오는 순열을 만든다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort
 
int main() {
    int myints[] = { 1,2,3 };
 
    std::sort(myints, myints + 3);
 
    std::cout << "The 3! possible permutations with 3 elements:\n";
    do {
        std::cout << myints[0<< ' ' << myints[1<< ' ' << myints[2<< '\n';
    } while (std::next_permutation(myints, myints + 3));
 
    std::cout << "After loop: " << myints[0<< ' ' << myints[1<< ' ' << myints[2<< '\n';
 
    return 0;
}
cs



7. heap

make_heap: 힙을 생성한다. (최대힙)

push_heap: 힙에 원소를 추가한다.

pop_heap: 힙에서 원소를 제거한다.

sort_heap: 힙을 정렬한다. 



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
#include <iostream>     // std::cout
#include <algorithm>    // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector>       // std::vector
 
int main() {
    int myints[] = { 10,20,30,5,15 };
    std::vector<int> v(myints, myints + 5);
 
    std::make_heap(v.begin(), v.end());
    std::cout << "initial max heap   : " << v.front() << '\n';
 
    std::pop_heap(v.begin(), v.end()); v.pop_back();
    std::cout << "max heap after pop : " << v.front() << '\n';
 
    v.push_back(99); std::push_heap(v.begin(), v.end());
    std::cout << "max heap after push: " << v.front() << '\n';
 
    std::sort_heap(v.begin(), v.end());
 
    std::cout << "final sorted range :";
    for (unsigned i = 0; i<v.size(); i++)
        std::cout << ' ' << v[i];
 
    std::cout << '\n';
 
    return 0;
}
cs




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

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

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

[STL] C++ STL algorithm2  (0) 2018.07.30
[STL] C++ STL algorithm1  (0) 2018.07.30
[STL] C++ STL multimap  (0) 2018.07.22
[STL] C++ STL map  (0) 2018.07.22
[STL] C++ STL multiset  (0) 2018.07.22

C++ algorithm


이번 글에서는 원소를 수정하는 알고리즘에서 몇가지를 알아본다.



1. fill(begin, end, value)

구간 [begin, end)를 value로 채운다.


fill 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>     // std::cout
#include <algorithm>    // std::fill
#include <vector>       // std::vector
 
int main() {
    std::vector<int> myvector(8);                       // myvector: 0 0 0 0 0 0 0 0
 
    std::fill(myvector.begin(), myvector.begin() + 45);   // myvector: 5 5 5 5 0 0 0 0
    std::fill(myvector.begin() + 3, myvector.end() - 28);   // myvector: 5 5 5 8 8 8 0 0
 
    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs



2. reverse(begin, end)

구간 [begin, end)의 순서를 역순으로 만든다.


reverse 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>     // std::cout
#include <algorithm>    // std::reverse
#include <vector>       // std::vector
 
int main() {
    std::vector<int> myvector;
 
    // set some values:
    for (int i = 1; i<10++i) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9
 
    std::reverse(myvector.begin(), myvector.end());    // 9 8 7 6 5 4 3 2 1
 
                                                       // print out content:
    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs



3. rotate(begin, mid, end)

구간 [begin, end)를 mid를 기준으로 왼쪽으로 회전시킨다. 

즉, begin에는 mid값이 들어가고, end-1에는 mid-1의 값이 들어간다.


rotate 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>     // std::cout
#include <algorithm>    // std::rotate
#include <vector>       // std::vector
 
int main() {
    std::vector<int> myvector;
 
    // set some values:
    for (int i = 1; i<10++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
 
    std::rotate(myvector.begin(), myvector.begin() + 3, myvector.end());
    // 4 5 6 7 8 9 1 2 3
    // print out content:
    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs



4. swap(a, b)

a와 b에 위치한 값을 바꾼다.


swap 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>     // std::cout
#include <algorithm>    // std::swap
#include <vector>       // std::vector
 
int main() {
 
    int x = 10, y = 20;                              // x:10 y:20
    std::swap(x, y);                              // x:20 y:10
 
    std::vector<int> foo(4, x), bar(6, y);       // foo:4x20 bar:6x10
    std::swap(foo, bar);                          // foo:6x10 bar:4x20
 
    std::cout << "foo contains:";
    for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs



5. unique(begin, end)

구간 [begin, end)에서 연속되는 같은 값 하나를 제외하고 제거

제거는 하지만 컨테이너의 크기를 줄이지는 않는다. (아래 예제에서 15번째 줄을 보면 제거한 뒤 쪽 공간은 남아있다)

제거한 뒤 end 이터레이터를 반환한다. (그래서 18번째 줄을 보면 end까지 벡터의 크기를 변경한다)


unique 사용 예제

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>     // std::cout
#include <algorithm>    // std::unique, std::distance
#include <vector>       // std::vector
 
bool myfunction(int i, int j) {
    return (i == j);
}
 
int main() {
    int myints[] = { 10,20,20,20,30,30,20,20,10 };           // 10 20 20 20 30 30 20 20 10
    std::vector<int> myvector(myints, myints + 9);
 
    // using default comparison:
    std::vector<int>::iterator it;
    it = std::unique(myvector.begin(), myvector.end());   // 10 20 30 20 10 ?  ?  ?  ?
                                                          //                ^
 
    myvector.resize(std::distance(myvector.begin(), it)); // 10 20 30 20 10
 
                                                          // using predicate comparison:
    std::unique(myvector.begin(), myvector.end(), myfunction);   // (no changes)
 
                                                                 // print out content:
    std::cout << "myvector contains:";
    for (it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs



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

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

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

[STL] C++ STL algorithm3  (0) 2018.07.30
[STL] C++ STL algorithm1  (0) 2018.07.30
[STL] C++ STL multimap  (0) 2018.07.22
[STL] C++ STL map  (0) 2018.07.22
[STL] C++ STL multiset  (0) 2018.07.22

C++ algorithm


알고리즘 시험 볼 때 유용하게 사용할 수 있는 STL이다.


레퍼런스 사이트에서 보면 각 함수들을 9가지 종류로 분류해 놓았다. 


이번 글에서는 그중 원소를 수정하지 않는 알고리즘(Non-modifying sequence) 중 몇가지를 알아본다.



1. count(begin, end, value) 

구간 [begin, end)에서 value의 원소 개수를 찾는다.


2. count_if(begin, end, f)

구간 [begin, end)에서 f 조건에 맞는 원소 개수를 찾는다.


count / count_if 예제


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>     // std::cout
#include <algorithm>    // std::count
#include <vector>       // std::vector
 
int main() {
    // counting elements in array:
    int myints[] = { 10,20,30,30,20,10,10,20 };   // 8 elements
    int mycount = std::count(myints, myints + 810); //10의 개수
    std::cout << "10 appears " << mycount << " times.\n";
 
    // counting elements in container:
    std::vector<int> myvector(myints, myints + 8);
    mycount = std::count(myvector.begin(), myvector.end(), 20); //20의 개수
    std::cout << "20 appears " << mycount << " times.\n";
 
    mycount = count_if(myvector.begin(), myvector.end(), [](int x) { return (x / 10) % 2 == 0; });//십의 자리 숫자가 짝수인 수의 개수
    std::cout << "myvector contains " << mycount << "\n";
 
    return 0;
}
cs




3. find(begin, end, value)

구간 [begin, end)에서 value와 같은 첫 번째 이터레이터를 찾는다.


4. find_if(begin, end, f)

구간 [begin, end)에서 f 조건에 해당하는 첫 번째 이터레이터


찾지 못하면 end를 반환


find / find_if 사용 예제


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
// find_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::find_if
#include <vector>       // std::vector
 
int main() {
    std::vector<int> myvector;
 
    myvector.push_back(10);
    myvector.push_back(25);
    myvector.push_back(40);
    myvector.push_back(55);
 
    std::vector<int>::iterator it;
 
    it = find(myvector.begin(), myvector.end(), 40);
    if (it != myvector.end())
        std::cout << "Element found in myvector: " << *it << '\n';
    else
        std::cout << "Element not found in myvector\n";
 
 
    it = find(myvector.begin(), myvector.end(), 100);
    if (it != myvector.end())
        std::cout << "Element found in myvector: " << *it << '\n';
    else
        std::cout << "Element not found in myvector\n";
 
    it = std::find_if(myvector.begin(), myvector.end(), [](int x) { return x % 2 == 1; });
    std::cout << "The first odd value is " << *it << '\n';
 
    return 0;
}
cs





5. max(a, b)

a와 b 중 더 큰 값 반환


6. min(a, b)

a와 b 중 더 작은 값 반환


max / min 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>     // std::cout
#include <algorithm>    // std::min / std::max
 
int main() {
    std::cout << "max(1,2)==" << std::max(12<< '\n';
    std::cout << "max(2,1)==" << std::max(21<< '\n';
    std::cout << "max('a','z')==" << std::max('a''z'<< '\n';
    std::cout << "max(3.14,2.72)==" << std::max(3.142.72<< "\n\n";
 
 
    std::cout << "min(1,2)==" << std::min(12<< '\n';
    std::cout << "min(2,1)==" << std::min(21<< '\n';
    std::cout << "min('a','z')==" << std::min('a''z'<< '\n';
    std::cout << "min(3.14,2.72)==" << std::min(3.142.72<< '\n';
    return 0;
}
cs



7. min_element / max_element

구간 [begin, end)에서 최소/최대값의 이터레이터를 반환한다.


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

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

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

[STL] C++ STL algorithm3  (0) 2018.07.30
[STL] C++ STL algorithm2  (0) 2018.07.30
[STL] C++ STL multimap  (0) 2018.07.22
[STL] C++ STL map  (0) 2018.07.22
[STL] C++ STL multiset  (0) 2018.07.22

C++ multimap


multimap을 사용하기 위해서는 <map>을 인클루드 해야한다.


map에서 중복된 key가 가능하다는 차이점 외에는 다 같다.  라고 책에는 나와있는데 multimap은 중복된 key를 허용하기 때문에, 앞서 map과는 다르게 [] 사용시 multimap에서는 오류가 발생한다. 이 차이점 외에는 다 같은것이 맞는 것 같다.


생성자 사용 예제

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 <map>
#include <functional>
 
int main()
{
    std::multimap<charint> first;
 
    first.insert(std::pair<charint>('a'10));
    first.insert(std::pair<charint>('b'30));
    first.insert(std::pair<charint>('c'50));
    first.insert(std::pair<charint>('d'70));
 
    std::multimap<charint> second(first.begin(), first.end());
 
    std::multimap<charint> third(second);
 
    std::multimap<charintstd::greater<int> > fourth = { { 'a'10 },{ 'b'30 },{ 'c'50 },{ 'd'70 } };
    
    std::cout << "first : ";
    for (auto it = first.begin(); it != first.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "second : ";
    for (auto it = second.begin(); it != second.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "third : ";
    for (auto it = third.begin(); it != third.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "fourth : ";
    for (auto it = fourth.begin(); it != fourth.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\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
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <map>
 
int main ()
{
  std::multimap<char,int> mymultimap;
  std::multimap<char,int>::iterator it;
 
  // first insert function version (single parameter):
  mymultimap.insert ( std::pair<char,int>('a',100) );
  mymultimap.insert ( std::pair<char,int>('z',150) );
  it=mymultimap.insert ( std::pair<char,int>('b',75) );
 
  // second insert function version (with hint position):
  mymultimap.insert (it, std::pair<char,int>('c',300));  // max efficiency inserting
  mymultimap.insert (it, std::pair<char,int>('z',400));  // no max efficiency inserting
 
  // third insert function version (range insertion):
  std::multimap<char,int> anothermultimap;
  anothermultimap.insert(mymultimap.begin(),mymultimap.find('c'));
 
  // showing contents:
  std::cout << "mymultimap contains:\n";
  for (it=mymultimap.begin(); it!=mymultimap.end(); ++it)
    std::cout << (*it).first << " => " << (*it).second << '\n';
 
  std::cout << "anothermultimap contains:\n";
  for (it=anothermultimap.begin(); it!=anothermultimap.end(); ++it)
    std::cout << (*it).first << " => " << (*it).second << '\n';
 
  return 0;
}
cs


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
#include <iostream>
#include <map>
 
int main ()
{
  std::multimap<char,int> mymultimap;
 
  // insert some values:
  mymultimap.insert(std::pair<char,int>('a',10));
  mymultimap.insert(std::pair<char,int>('b',20));
  mymultimap.insert(std::pair<char,int>('b',30));
  mymultimap.insert(std::pair<char,int>('c',40));
  mymultimap.insert(std::pair<char,int>('d',50));
  mymultimap.insert(std::pair<char,int>('d',60));
  mymultimap.insert(std::pair<char,int>('e',70));
  mymultimap.insert(std::pair<char,int>('f',80));
 
  std::multimap<char,int>::iterator it = mymultimap.find('b');
 
  mymultimap.erase (it);                     // erasing by iterator (1 element)
 
  mymultimap.erase ('d');                    // erasing by key (2 elements)
 
  it=mymultimap.find ('e');
  mymultimap.erase ( it, mymultimap.end() ); // erasing by range
 
  // show content:
  for (it=mymultimap.begin(); it!=mymultimap.end(); ++it)
    std::cout << (*it).first << " => " << (*it).second << '\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
22
23
24
25
#include <iostream>
#include <map>
 
int main ()
{
  std::multimap<char,int> mymm;
 
  mymm.insert(std::make_pair('x',50));
  mymm.insert(std::make_pair('y',100));
  mymm.insert(std::make_pair('y',150));
  mymm.insert(std::make_pair('y',200));
  mymm.insert(std::make_pair('z',250));
  mymm.insert(std::make_pair('z',300));
 
  for (char c='x'; c<='z'; c++)
  {
    std::cout << "There are " << mymm.count(c) << " elements with key " << c << ":";
    std::multimap<char,int>::iterator it;
    for (it=mymm.equal_range(c).first; it!=mymm.equal_range(c).second; ++it)
      std::cout << ' ' << (*it).second;
    std::cout << '\n';
  }
 
  return 0;
}
cs



참조: http://www.cplusplus.com/reference/map/multimap/

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

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

[STL] C++ STL algorithm2  (0) 2018.07.30
[STL] C++ STL algorithm1  (0) 2018.07.30
[STL] C++ STL map  (0) 2018.07.22
[STL] C++ STL multiset  (0) 2018.07.22
[STL] C++ STL set  (0) 2018.07.22

C++ map


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


key와 value를 쌍으로 저장한다.


set과 마찬가지로 key를 중복으로 저장할 수 없으며, 중복된 key를 이용하려면 multimap을 이용하면 된다.


map은 []연산자를 이용하여 key에 접근할 수 있다.


map은 pair객체로 원소를 저장하기 때문에, 첫번째 key는 first로 두번째 value는 second로 접근할 수 있다.


생성자 사용 예제

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
#include <iostream>
#include <map>
#include <functional>
 
int main()
{
    std::map<charint> first;
 
    first['a'= 10;
    first['b'= 30;
    first['c'= 50;
    first['d'= 70;
 
    std::map<charint> second(first.begin(), first.end());
 
    std::map<charint> third(second);
 
    std::map<charintstd::greater<int> > fourth = { {'a'10}, {'b'30}, {'c'50}, {'d'70} }; 
 
    std::cout << "first : ";
    for (auto it = first.begin(); it != first.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "second : ";
    for (auto it = second.begin(); it != second.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "third : ";
    for (auto it = third.begin(); it != third.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "fourth : ";
    for (auto it = fourth.begin(); it != fourth.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <map>
 
int main()
{
    std::map<charint> mymap;
 
    // first insert function version (single parameter):
    mymap.insert(std::pair<charint>('a'100));
    mymap.insert(std::pair<charint>('z'200));
 
    std::pair<std::map<charint>::iteratorbool> ret;
    ret = mymap.insert(std::pair<charint>('z'500));
    if (ret.second == false) {
        std::cout << "element 'z' already existed";
        std::cout << " with a value of " << ret.first->second << '\n';
    }
 
    // second insert function version (with hint position):
    std::map<charint>::iterator it = mymap.begin();
    mymap.insert(it, std::pair<charint>('b'300));  // max efficiency inserting
    mymap.insert(it, std::pair<charint>('c'400));  // no max efficiency inserting
 
                                                       // third insert function version (range insertion):
    std::map<charint> anothermap;
    anothermap.insert(mymap.begin(), mymap.find('c'));
 
    // showing contents:
    std::cout << "mymap contains:\n";
    for (it = mymap.begin(); it != mymap.end(); ++it)
        std::cout << it->first << " => " << it->second << '\n';
 
    std::cout << "anothermap contains:\n";
    for (it = anothermap.begin(); it != anothermap.end(); ++it)
        std::cout << it->first << " => " << it->second << '\n';
 
    return 0;
}
cs


find(), 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
#include <iostream>
#include <map>
 
int main ()
{
  std::map<char,int> mymap;
  std::map<char,int>::iterator it;
 
  // insert some values:
  mymap['a']=10;
  mymap['b']=20;
  mymap['c']=30;
  mymap['d']=40;
  mymap['e']=50;
  mymap['f']=60;
 
  it=mymap.find('b');
  mymap.erase (it);                   // erasing by iterator
 
  mymap.erase ('c');                  // erasing by key
 
  it=mymap.find ('e');
  mymap.erase ( it, mymap.end() );    // erasing by range
 
  // show content:
  for (it=mymap.begin(); it!=mymap.end(); ++it)
    std::cout << it->first << " => " << it->second << '\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
22
23
#include <iostream>
#include <map>
 
int main ()
{
  std::map<char,int> mymap;
  char c;
 
  mymap ['a']=101;
  mymap ['c']=202;
  mymap ['f']=303;
 
  for (c='a'; c<'h'; c++)
  {
    std::cout << c;
    if (mymap.count(c)>0)
      std::cout << " is an element of mymap.\n";
    else 
      std::cout << " is not an element of mymap.\n";
  }
 
  return 0;
}
cs


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

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

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

[STL] C++ STL algorithm1  (0) 2018.07.30
[STL] C++ STL multimap  (0) 2018.07.22
[STL] C++ STL multiset  (0) 2018.07.22
[STL] C++ STL set  (0) 2018.07.22
[STL] C++ STL string to int/float/double/long long  (0) 2018.07.19

C++ multiset


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


중복된 데이터를 사용할 수 있는 것 외에는 set과 모두 같다.




 생성자

 

 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 조건자를 사용


생성자 사용 예제



#include <iostream>
#include <set>
#include <functional>
int main()
{
    std::multiset<int> first;                           // empty set of ints
 
    int myints[] = { 10203040502030405060 };
    std::multiset<int> second(myints, myints + 10);        // range
 
    std::multiset<int> third(second);                  // a copy of second
 
    std::multiset<int> fourth(second.begin(), second.end());  // iterator ctor.
 
    std::multiset<intstd::greater<int> > fifth = { 10203040502030405060 };
 
    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()


#include <iostream>
#include <set>
 
int main()
{
    std::multiset<int> mymultiset;
    std::multiset<int>::iterator it;
 
    // set some initial values:
    for (int i = 1; i <= 5; i++) mymultiset.insert(i * 10);  // 10 20 30 40 50
 
    it = mymultiset.insert(25);
 
    it = mymultiset.insert(it, 27);    // max efficiency inserting
    it = mymultiset.insert(it, 29);    // max efficiency inserting
    it = mymultiset.insert(it, 24);    // no max efficiency inserting (24<29)
 
    int myints[] = { 5,10,15 };
    mymultiset.insert(myints, myints + 3);
 
    std::cout << "mymultiset contains:";
    for (it = mymultiset.begin(); it != mymultiset.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs



erase(), find()


#include <iostream>
#include <set>
 
int main ()
{
  std::multiset<int> mymultiset;
  std::multiset<int>::iterator it;
 
  // insert some values:
  mymultiset.insert (40);                            // 40
  for (int i=1; i<7; i++) mymultiset.insert(i*10);   // 10 20 30 40 40 50 60
 
  it=mymultiset.begin();
  it++;                                              //    ^
 
  mymultiset.erase (it);                             // 10 30 40 40 50 60
 
  mymultiset.erase (40);                             // 10 30 50 60
 
  it=mymultiset.find (50);
  mymultiset.erase ( it, mymultiset.end() );         // 10 30
 
  std::cout << "mymultiset contains:";
  for (it=mymultiset.begin(); it!=mymultiset.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';
 
  return 0;
}
cs


count()


#include <iostream>
#include <set>
 
int main ()
{
  int myints[]={10,73,12,22,73,73,12};
  std::multiset<int> mymultiset (myints,myints+7);
 
  std::cout << "73 appears " << mymultiset.count(73<< " times in mymultiset.\n";
 
  return 0;
}
cs



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

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

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

[STL] C++ STL multimap  (0) 2018.07.22
[STL] C++ STL map  (0) 2018.07.22
[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 list  (0) 2018.07.19

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

+ Recent posts