기술 블로그

vector 간단한 insert, erase 본문

C++ STL

vector 간단한 insert, erase

parkit 2018. 12. 9. 01:29
728x90
반응형

맨 마지막 원소삭제할 때만 주의하면 된다.


v.end()가 아니라 v.end() - 1이다. 


단, insert 할 때, 맨 마지막 끝에 삽입 할 때에는 v.end()이다.


vector의 insert와 erase를 활용한 문제도 풀어보자.(물론 다른 방법의 풀이도 있다.)

문제 : https://www.acmicpc.net/problem/1021

정답 : http://hsdevelopment.tistory.com/163



실행 결과

원래의 vector = 1 2 3 4 5 6 7 8 9 10

맨 앞 원소 삭제 = 2 3 4 5 6 7 8 9 10

두 번째 원소 삭제 = 2 4 5 6 7 8 9 10

끝 원소 삭제 = 2 4 5 6 7 8 9

숫자 8 삭제 = 2 4 5 6 7 9

제일 처음에 숫자 1 삽입 = 1 2 4 5 6 7 9

제일 끝에 숫자 10 삽입 = 1 2 4 5 6 7 9 10

오름차순 되게 숫자 3 삽입 = 1 2 3 4 5 6 7 9 10



insert와 erase 예제 소스코드 파일(.cpp)도 첨부하였다.



vector insert erase.cpp




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
64
65
66
67
68
69
70
71
#include <iostream>
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <cstring>
#include <string>
#include <math.h>
#include <algorithm>
#include <map>
 
using namespace std;
 
int main(void)
{
    vector<int> v;
 
    printf("원래의 vector = ");
 
    for (int i = 1; i <= 10; i++)
    {
        v.push_back(i);
 
        printf("%d ", i);
    }
    printf("\n");
 
    printf("맨 앞 원소 삭제 = ");
    v.erase(v.begin());
    for (auto i : v) printf("%d ", i);
    printf("\n");
 
    printf("두 번째 원소 삭제 = ");
    v.erase(v.begin() + 1);
    for (auto i : v) printf("%d ", i);
    printf("\n");
 
    printf("끝 원소 삭제 = ");
    v.erase(v.end() - 1);
    for (auto i : v) printf("%d ", i);
    printf("\n");
 
    printf("숫자 8 삭제 = ");    
    for (int i = 0; i < v.size(); i++)
    {
        if (v.at(i) == 8)
        {
            v.erase(v.begin() + i);
            break;
        }
    }
    for (auto i : v) printf("%d ", i);
    printf("\n");
 
    printf("제일 처음에 숫자 1 삽입 = ");
    v.insert(v.begin(), 1);
    for (auto i : v) printf("%d ", i);
    printf("\n");
 
    printf("제일 끝에 숫자 10 삽입 = ");
    v.insert(v.end(), 10);
    for (auto i : v) printf("%d ", i);
    printf("\n");
 
    printf("오름차순 되게 숫자 3 삽입 = ");
    v.insert(v.begin() + 23);
    for (auto i : v) printf("%d ", i);
    printf("\n");
 
    return 0;
}
cs




728x90
반응형

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

#include <map>  (0) 2019.03.22
#include <tuple>  (0) 2019.03.18
2차원 배열 fill로 초기화.(feat memset)  (2) 2019.01.10
next_permutation  (0) 2019.01.09
vector<pair<int, int> > v; 정렬하는 방법  (0) 2018.11.28