insert() 함수는 다양한 STL 컨테이너(벡터, 리스트, 문자열, 맵, 셋 등)에서 새로운 요소를 삽입할 수 있다. 각 컨테이너에 따라 동작 방식과 삽입 위치가 달라지며, 오버로드된 여러 버전의 insert() 함수가 존재한다.
iterator insert(const_iterator pos, const T& value);
iterator insert(const_iterator pos, size_type count, const T& value);
template <class InputIterator>
iterator insert(const_iterator pos, InputIterator first, InputIterator last);
pos : 삽입할 위치를 가리키는 반복자value : 삽입할 값count : 삽입할 횟수first, last : 삽입할 범위를 나타내는 반복자#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 5};
vec.insert(vec.begin() + 3, 4);
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
출력:
1 2 3 4 5
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {10, 20, 30};
// 3번 반복하여 25를 삽입
vec.insert(vec.begin() + 1, 3, 25);
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
출력:
10 25 25 25 20 30
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec1 = {1, 2, 3};
std::vector<int> vec2 = {4, 5, 6};
// vec2의 모든 요소를 vec1의 끝에 삽입
vec1.insert(vec1.end(), vec2.begin(), vec2.end());
for (int num : vec1) {
std::cout << num << " ";
}
return 0;
}
출력:
1 2 3 4 5 6
std::list의 insert() 함수는 벡터와 유사하게 동작하지만, 리스트는 연결 리스트 구조이기 때문에 삽입이 O(1) 시간 복잡도로 매우 빠르다다.
#include <iostream>
#include <list>
int main() {
std::list<int> lst = {10, 20, 40};
// 30을 2번째 위치에 삽입
auto it = lst.begin();
std::advance(it, 2); // 반복자를 2칸 전진
lst.insert(it, 30);
for (int num : lst) {
std::cout << num << " ";
}
return 0;
}
출력:
10 20 30 40
std::string 클래스의 insert() 함수는 문자열에 새로운 문자를 삽입할 때 사용된다.
string& insert(size_t pos, const string& str);
string& insert(size_t pos, const char* s);
string& insert(size_t pos, size_t count, char ch);
pos: 삽입할 시작 위치str: 삽입할 문자열s: 삽입할 C 스타일 문자열count: 삽입할 문자 수ch: 삽입할 문자#include <iostream>
#include <string>
int main() {
std::string str = "Hello World";
// "Beautiful "을 6번째 위치에 삽입
str.insert(6, "Beautiful ");
std::cout << str << std::endl;
return 0;
}
출력:
Hello Beautiful World
#include <iostream>
#include <string>
int main() {
std::string str = "Hello";
// 3번 반복하여 문자 '!' 삽입
str.insert(5, 3, '!');
std::cout << str << std::endl;
return 0;
}
출력:
Hello!!!
std::map과 std::set에서는 insert() 함수가 새로운 키-값 쌍 또는 새로운 요소를 삽입하는 역할을 한다. 삽입할 때 중복된 키나 값은 허용되지 않으며, 삽입 결과를 나타내는 std::pair 객체를 반환한다.
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap.insert({1, "Apple"});
myMap.insert({2, "Banana"});
// 중복된 키 삽입 시도
auto result = myMap.insert({1, "Cherry"});
if (!result.second) {
std::cout << "키 1에 해당하는 값이 이미 존재합니다." << std::endl;
}
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
출력:
1: Apple
2: Banana
키 1에 해당하는 값이 이미 존재합니다.