---
title: "map注意的两个问题"
author: "美丽的小岛"
date: "2014-12-11T14:21:02Z"
tags: []
categories: ["编程语言"]
slug: "map"
draft: false
lastmod: "2014-12-11T14:21:02Z"
id: 2165158
url: "https://happyprince.iteye.com/blog/2165158"
---

```
代码1
void main() 
{

        map< int, int* > mapInt;

        for ( int i = 0; i < 5; i++ )
         {

               mapInt[ i ] = new int( i );
        }

        // 再插入键值为2的元素

        mapInt[ 2 ] = new int( 2 );

        // 做一些操作

        // 删除内存。

        map< int, int* >::iterator itMap = mapInt.begin();

        for ( ; itMap != mapInt.end(); ++itMap ) {

                delete itMap->second;

        }
}
```

 

 

```
代码2
void main() {

     map< int, int > mapInt;

     for ( int i = 0; i < 5; i++ ) 
     {

          mapInt.insert( make_pair( i, i ) );

     }

     mapInt.insert( make_pair( 5, 2 ) );

     // 删除所有实值为2的元素

     map< int, int >::iterator itMap = mapInt.begin();

     for ( ; itMap != mapInt.end(); ++itMap )
     {

           if ( itMap->second == 2 )
           {
                  mapInt.erase( itMap );
              }
       }
}
```

 

**代码1**   将导致内存泄露，因为mapInt\[ 2 ] = new int( 2 );这条语句把原来键值为2的元素的实值指针覆盖了，原来的指针就成为野指针，导致内存泄露。  
map容器插入元素的方法。可以调用map容器的insert成员函数插入元素，或者直接用map容器的下标运算式赋值，但这里有一个地方要注意，如果实值为指针的话，插入重复键值的元素时，会导致内存泄露。所以对于插入元素时，必须检查是否插入成功。

正确的方法：  
void main() {   
map&lt; int, int* &gt; mapInt;  
bool bRet;  
for ( int i = 0; i &lt; 5; i++ ) {  
int* pI = new int( i );  
bRet = mapInt.insert( make\_pair( i, pI ) ).second;  
if ( !bRet ) {  
// 插入元素不成功。  
delete pI;  
}  
}  
// 再插入键值为2的元素  
int* pI = new int( 2 );  
bRet = mapInt.insert( make\_pair( 2, pI ) ).second;  
if ( !bRet ) {  
// 插入元素不成功。  
delete pI;  
}  
// 做一些操作  
// 删除内存。  
map&lt; int, int* &gt;::iterator itMap = mapInt.begin();  
for ( ; itMap != mapInt.end(); ++itMap ) {  
delete itMap-&gt;second;  
}  
}

 

**代码2** 将导致程序未定义的错误，在windows中即是访问非法内存，程序当掉。因为mapInt.erase( itMap );调用后itMap迭代器已无效了，所以当执行++itMap时，访问非法内存，导致程序当掉。

如果erase（）总是返回下一元素的位置，那就可以像在vector容器中删除元素一样，如：

// 删除所有实值为2的元素

map&lt; int, int &gt;::iterator itMap = mapInt.begin();

for ( ; itMap != mapInt.end(); ) {

if ( itMap-&gt;second == 2 ) {

itMap = mapInt.erase( itMap ); 

}

else {

++itMap;  
}  
}

但是，注意，以上的方式只在vc使用P.J.STL中才能编译通过，而使用SGI STL库则编译不过，因为SGISTL库在设计中考虑到如果用户不需要这一特性，就会损失性能，因此否决了这种想法。所以要保证可移植性，最好采用下面的方法：

// 删除所有实值为2的元素

map&lt; int, int &gt;::iterator itMap = mapInt.begin();

for ( ; itMap != mapInt.end(); ) {

if ( itMap-&gt;second == 2 ) {

// itMap++将使itMap指向下一个元素，但返回原迭代器的副本，所以

// erase（）被调用时，itMap不指向将要被删除的元素

mapInt.erase( itMap++ ); 

}

else {

++itMap;

}

}