1. 추 가(insert)
map에서는 자료를 추가 할 때 isnert를 사용한다.
원 형 :
pair < iterator, bool > insert( const value_type& _Val );
iterator insert( iterator _Where, const value_type& _Val );
template< class InputIterator > void insert( InputIterator _First, InputIterator _Last );
1.map < int, int > map1; // key는 1, value 35를 추가 map1.insert( map < int, int > :: value_type( 1, 35 ) ); // 또는 STL의 pair를 사용하기도 한다. typedef pair< int, int > Int_Pair; map1.insert( Int_Pair(2, 45) );
// 특정 위치에 추가 할 수도 있다. // 첫 번째 위치에 key 1, value 35를 추가 map1.insert( map1.begin(), map< int, int > :: value_type( 1, 35 ); // 또는 map1.insert( map1.begin(), Int_Pair( 2, 45 ));
// 지정한 반복자 구간에 있는 것들을 추가한다. map< int, int > map2; // map1의 모든 요소를 map2에 추가 map2.insert( map1.begin(), map1.end() );
map은 이미 있는 key값을 추가할 수 없다.
(복수의 key값을 사용하기 위해서는 multi map을 사용해야 한다!)
가장 자주 사용하는 첫 번째 방식을 추가하는 경우는 아래와 같은 방법이 있다.pair< map< int, int >:: iterator, bool > Result; Result = map1.insert( Int_Pair( 1, 35 ) );
key 값 1이 추가되어 있었다면,
insert는 실패하기 때문에 Result.second는 false를 리턴,
반대로 성공하면 true를 리턴한다.
4.// insert가 아닌 operator[]를 사용하여 추가할 수도 있다. // key 10, value 80을 추가 map1[10] = 80;