Vector
C++의 vector는 동적 배열(dynamic array)을 구현하기 위한 STL(Standard Template Library) 컨테이너입니다.
vector는 배열과 마찬가지로 요소들이 메모리에 연속적으로 저장되며, 크기를 동적으로 조절할 수 있어 효율적인 메모리 사용이 가능합니다.
vector를 사용하기 위해서는 다음과 같이 헤더 파일 <vector>을 include해야 합니다:
#include <vector>
관련 함수
push_back()
vector의 맨 뒤에 새로운 요소를 추가합니다.
#include <vector>
#include <iostream>
int main() {
std::vector<int> v{1, 2, 3};
v.push_back(4);
for (int i : v) {
std::cout << i << " "; // 출력 결과: 1 2 3 4
}
return 0;
}
pop_back()
vector의 맨 뒤에 있는 요소를 제거합니다.
#include <vector>
#include <iostream>
int main() {
std::vector<int> v{1, 2, 3};
v.pop_back();
for (int i : v) {
std::cout << i << " "; // 출력 결과: 1 2
}
return 0;
}
size()
vector의 요소 개수를 반환합니다.
#include <vector>
#include <iostream>
int main() {
std::vector<int> v{1, 2, 3};
std::cout << v.size() << std::endl; // 출력 결과: 3
return 0;
}
at()
vector의 특정 인덱스에 해당하는 요소를 반환합니다. 범위를 벗어나는 인덱스를 사용하면 예외를 발생시킵니다.
#include <vector>
#include <iostream>
int main() {
std::vector<int> v{1, 2, 3};
std::cout << v.at(1) << std::endl; // 출력 결과: 2
// std::cout << v.at(3) << std::endl; // 범위를 벗어나는 인덱스 사용 예시
return 0;
}
clear()
vector의 모든 요소를 제거합니다.
#include <vector>
#include <iostream>
int main() {
std::vector<int> v{1, 2, 3};
v.clear();
std::cout << v.size() << std::endl; // 출력 결과: 0
return 0;
}
front()와 back()
각각 vector의 첫 번째 요소와 마지막 요소에 대한 참조를 반환합니다.
#include <vector>
#include <iostream>
int main() {
std::vector<int> v{1, 2, 3};
v.front() = 4;
std::cout << v.front() << std::endl; // 출력 결과: 4
v.back() = 5;
std::cout << v.back() << std::endl; // 출력 결과: 5
return 0;
}
'백준 > 이론_C++' 카테고리의 다른 글
SET 자료구조 사용법 C++ (0) | 2023.04.16 |
---|---|
문자열 뒤집기 C++ (0) | 2023.04.11 |
댓글