본문 바로가기
Languages/C++

[C++ STL] Vector

by chuckolet 2018. 12. 28.

Introduction

벡터(Vector)란 원소가 삽입 또는 제거 됐을 때 컨테이너에 의해서 자동으로 저장 공간이 조절 되는 동적 배열과 같습니다. 벡터의 원소들은 인접한 메모리 공간에 저장되기 때문에 iterator를 이용해서 접근하거나 순회 할 수 있죠. 벡터에서 데이터는 끝 쪽으로 삽입 됩니다. 마지막 위치에 삽입하는 작업은 배열을 연장하고 삽입해야 하는 경우도 있기 때문에 차등적으로 시간이 소요됩니다. 하지만 마지막 원소를 제거할 때는 리사이징 할 필요가 없기 때문에 항상 일정한 시간이 소요됩니다. 처음 또는 중간 부분에 삽입, 제거하는 작업은 시간이 선형적으로 소요됩니다.


Basic operations

Iterators

1. begin(): 벡터의 첫번째 원소를 가리키는 iterator를 리턴합니다.
2. end(): 벡터에서 마지막 원소 다음을 가리키는 iterator를 리턴합니다.

cf) 앞에 c가 붙은 함수는 constant, r이 붙은 함수는 reverse입니다.


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 <iostream>
#include <vector>
using namespace std;
 
int main() {
    vector<int> v;
    
    for (int i = 1; i <= 5; i++)
        v.push_back(i);
        
    cout << "Output of begin and end: ";
    for (vector<int>::iterator i = v.begin(); i != v.end(); i++)
        cout << *<< " ";
        
    cout << "\nOutput of cbegin and cend: "
    for (auto i = v.cbegin(); i != v.cend(); i++
        cout << *<< " ";
    
    cout << "\nOutput of rbegin and rend: "
    for (auto ir = v.rbegin(); ir != v.rend(); ir++)
        cout << *ir << " ";
        
    cout << "\nOutput of crbegin and crend : "
    for (auto ir = v.crbegin(); ir != v.crend(); ++ir) 
        cout << *ir << " "
        
    return 0;
}
cs


1
2
3
4
Output of begin and end: 1 2 3 4 5 
Output of cbegin and cend: 1 2 3 4 5 
Output of rbegin and rend: 5 4 3 2 1 
Output of crbegin and crend : 5 4 3 2 1
cs





Capacity

1. size(): 벡터 내의 원소들의 개수를 리턴합니다.
2. max_size(): 벡터가 가질 수 있는 최대 원소 개수를 리턴합니다.
3. empty(): 컨테이너가 비어있으면 true, 비어있지 않으면 false를 리턴합니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
using namespace std;
 
int main() {
    vector<int> v;
    
    for (int i = 1; i <= 5; i++)
        v.push_back(i);
    
    cout << "Size: " << v.size();
    
    // checks if the vector is empty or not 
    if (v.empty() == false
        cout << "\nVector is not empty"
    else
        cout << "\nVector is empty"
        
    return 0;
}
cs


1
2
Size: 5
Vector is not empty
cs


Element access

1. at(v): 벡터 내에서 'v' 위치에 있는 원소의 주소를 리턴합니다.
2. front(): 벡터의 첫번째 원소의 주소를 리턴합니다.
3. back(): 벡터의 마지막 원소의 주소를 리턴합니다.
4. data(): 가지고 있는 요소를 저장하기 위해 벡터에서 내부적으로 사용되는 메모리 배열에 대한 직접 포인터를 반환합니다.

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 <vector>
using namespace std;
 
int main() {
    vector<int> v1;
    
    for (int i = 1; i <= 5; i++)
        v1.push_back(i * 10);
        
    cout << "\nOutput of begin and end: ";
    for (vector<int>::iterator i = v1.begin(); i != v1.end(); i++)
        cout << *<< " ";
        
    cout << "\nReference operator [v]: v1[2] = " << v1[2];
    cout << "\nat: v1.at(4) = " << v1.at(4);
    cout << "\nfront(): v1.front() = " << v1.front();
    cout << "\nback(): v1.back() = " << v1.back();
        
    // 첫번째 원소에 대한 포인터
    int* pos = v1.data();
    
    cout << "\nThe first element is " << *pos;
    
    return 0;
}
cs

1
2
3
4
5
6
Output of begin and end: 10 20 30 40 50 
Reference operator [v]: v1[2] = 30
at: v1.at(4) = 50
front(): v1.front() = 10
back(): v1.back() = 50
The first element is 10
cs

Modifiers

1. assign(): 이전의 벡터 원소를 새로운 값으로 바꿔준다.

2. push_back(): 벡터의 맨 뒤에 원소를 넣어준다.

3. pop_back(): 벡터의 맨 마지막 원소를 제거한다.

4. insert(): 특정 위치의 원소 앞에 새로운 원소를 삽입한다.

5. erase(): 특정 위치 또는 범위의 원소들을 제거한다.

6. swap(): 같은 종류면서 같은 크기를 가진 다른 벡터와 내용물을 교체한다.

7. clear(): 벡터 컨테이너의 모든 원소를 제거한다.

8. emplace(): 특정 위치에 새로운 원소를 삽입하면서 컨테이너 크기를 늘려준다.

9. emplace_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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <vector>
using namespace std;
 
int main() {
    vector<int> v;
    
    // 10을 5번 채워준다.
    v.assign(510);
        
    cout << "\nThe vector elements are: ";
    for (vector<int>::iterator i = v.begin(); i != v.end(); i++)
        cout << *<< " ";
        
    v.push_back(15);
    int n = v.size();
    cout << "\nThe vector elements are: ";
    for (vector<int>::iterator i = v.begin(); i != v.end(); i++)
        cout << *<< " ";
    
    v.pop_back();
    cout << "\nThe vector elements are: ";
    for (vector<int>::iterator i = v.begin(); i != v.end(); i++)
        cout << *<< " ";
        
    v.insert(v.begin(), 5);
    cout << "\nThe vector elements are: ";
    for (vector<int>::iterator i = v.begin(); i != v.end(); i++)
        cout << *<< " ";
        
    v.erase(v.begin());
    cout << "\nThe vector elements are: ";
    for (vector<int>::iterator i = v.begin(); i != v.end(); i++)
        cout << *<< " ";
        
    v.emplace(v.begin(), 5);
    cout << "\nThe vector elements are: ";
    for (vector<int>::iterator i = v.begin(); i != v.end(); i++)
        cout << *<< " ";
    
    v.emplace_back(20);
    cout << "\nThe vector elements are: ";
    for (vector<int>::iterator i = v.begin(); i != v.end(); i++)
        cout << *<< " ";
        
    v.clear();
    cout << "\nVector size after erase(): " << v.size();
    
    // swap할 두 개의 벡터 생성
    vector<int> v1, v2;
    v1.push_back(1);
    v1.push_back(2);
    v2.push_back(3);
    v2.push_back(4);
    
    cout << "\n\nVector 1: ";
    for (int i = 0; i < v1.size(); i++
        cout << v1[i] << " ";
    
    cout << "\nVector 2: ";
    for (int i = 0; i < v1.size(); i++
        cout << v2[i] << " ";
        
    v1.swap(v2);
    
        cout << "\n\nVector 1: ";
    for (int i = 0; i < v1.size(); i++
        cout << v1[i] << " ";
    
    cout << "\nVector 2: ";
    for (int i = 0; i < v1.size(); i++
        cout << v2[i] << " ";
    
    return 0;
}
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
The vector elements are: 10 10 10 10 10 
The vector elements are: 10 10 10 10 10 15 
The vector elements are: 10 10 10 10 10 
The vector elements are: 5 10 10 10 10 10 
The vector elements are: 10 10 10 10 10 
The vector elements are: 5 10 10 10 10 10 
The vector elements are: 5 10 10 10 10 10 20 
Vector size after erase(): 0
 
Vector 1: 1 2 
Vector 2: 3 4 
 
Vector 1: 3 4 
Vector 2: 1 2 
cs

References

https://www.geeksforgeeks.org/vector-in-cpp-stl/


제 글이 도움이 되셨다면 간단하게 '공감', '댓글' 부탁드립니다!



댓글