'C++' std::insert

토스트·2025년 4월 29일

'C++' std::vector

목록 보기
5/6

1. 단일 요소 삽입

iterator insert(const_iterator position, const value_type& val);

: position에 있는 요소 앞에 val의 복사본을 삽입하고 삽입된 위치를 반환합니다.

<예시 코드>

#include <iostream>
#include <vector>

using namespace std;

int main() {
	vector<int> vec;

	vec.insert(vec.begin(), 3);

	cout << vec[0];

	return 0;
}

결과

2. 채우기 삽입

iterator insert(const_iterator position, size_type n, const value_type& val);

: position에 있는 요소 앞에 n개의 val를 삽입하고 삽입된 위치를 반환합니다.

<예시 코드>

#include <iostream>
#include <vector>

using namespace std;

int main() {
	vector<int> vec;

	vec.insert(vec.begin(), 3, 7);

	for (const int& i : vec) {
		cout << i << ' ';
	}

	return 0;
}

결과

3. 범위 삽입

template<class InputIterator>
iterator insert(const_iterator position, InputIterator first, InputIterator last);

: position에 있는 요소 앞에 [first, last) 범위의 요소를 삽입하고 삽입된 위치를 반환합니다.

<예시 코드>

#include <iostream>
#include <vector>

using namespace std;

int main() {
	vector<int> vec1 = { 1, 2, 3, 4 };
	vector<int> vec2 = { 4, 3, 2, 1 };
	
	vec1.insert(vec1.begin() + 1, vec2.begin(), vec2.end() - 1);

	for (const int& i : vec1) {
		cout << i << ' ';
	}

	return 0;
}

결과

4. 단일 요소 이동 삽입

iterator insert(const_iterator position, value_type&& val);

: position에 있는 요소 앞에 val를 이동시켜 삽입하고 삽입된 위치를 반환합니다.

<예시 코드>

#include <iostream>
#include <vector>

using namespace std;

int main() {
	vector<int> vec = { 1, 2, 3, 4 };
	
	int num = 7;

	vec.insert(vec.begin() + 1, move(num));

	for (const int& i : vec) {
		cout << i << ' ';
	}

	return 0;
}

결과

5. 초기화 목록 삽입

iterator insert(const_iterator position, initializer_list<value_type> il);

: position에 있는 요소 앞에 il의 각 요소를 동일한 순서로 삽입하고 삽입된 위치를 반환합니다.

<예시 코드>

#include <iostream>
#include <vector>

using namespace std;

int main() {
	vector<int> vec = { 1, 2, 3, 4 };

	vec.insert(vec.begin() + 2, {5, 2, 0});

	for (const int& i : vec) {
		cout << i << ' ';
	}

	return 0;
}

결과

0개의 댓글