[C++] try_emplace/insert_or_assign
Updated:
개요
- try_emplace
- 컨테이너에 요소가 없는 경우 새 요소를 삽입
- 컨테이너에 요소가 있는 경우 변경하지 않음
- insert_or_assign
- 컨테이너에 요소가 없는 경우 새 요소를 삽입
- 컨테이너에 요소가 있는 경우 덮어쓰기
예제
- 코드
#include <iostream> #include <map> #include <string> using namespace std; void try_emplace_test() { map<int, string> m; m.try_emplace(1, "a"); m.try_emplace(2, "b"); m.try_emplace(2, "c"); for (const auto &iter : m) { cout << iter.first << ", " << iter.second << endl; } } void insert_or_assign_test() { map<int, string> m; m.insert_or_assign(1, "a"); m.insert_or_assign(2, "b"); m.insert_or_assign(2, "c"); for (const auto &iter : m) { cout << iter.first << ", " << iter.second << endl; } } int main() { try_emplace_test(); cout << "------" << endl; insert_or_assign_test(); return 0; }
- 실행 결과
1, a 2, b ------ 1, a 2, c