1. 系统/基本头文件
2. 其他工程头文件
3. 本工程头文件
4. 本类头文件.
类定义中的成员变脸和成员函数排列顺序
1. 枚举/结构体, 固定使用public类型, 排在最前
2. private 成员变量
3. protected 成员变量
4. public 成员变量
5. private 成员函数
6. protected 成员函数
7. public 成员函数
8. 静态成员函数
细分顺序
本类const成员函数
本类非const成员函数
本类const虚函数
本类非const虚函数
基类const成员函数
基类非const成员函数
点击(此处)折叠或打开 迭代器的使用范例.
-
#include <iostream>
-
#include <map>
-
using namespace std;
-
-
class CMapExa
-
{
-
public:
-
void OnInit();
-
void DelFunConfuse();
-
void DelFunCorrect();
-
void Show();
-
private:
-
typedef map<int, int> MAP_DATA;
-
MAP_DATA m_map;
-
};
-
-
void CMapExa::OnInit()
-
{
-
m_map.insert(MAP_DATA::value_type(1,1));
-
m_map.insert(MAP_DATA::value_type(2,2));
-
m_map.insert(MAP_DATA::value_type(3,3));
-
}
-
-
void CMapExa::DelFunConfuse() //不好的方式
-
{
-
for (MAP_DATA::iterator it = m_map.begin(); it != m_map.end();)
-
{
-
m_map.erase(it++); //容易错误使用为 m_map.erase(it);
-
}
-
}
-
-
void CMapExa::DelFunCorrect() //建议的方式
-
{
-
MAP_DATA delMap;
-
for (MAP_DATA::iterator it = m_map.begin(); it != m_map.end(); ++it) {
-
delMap[it->first] = it->second;
-
}
-
-
for (MAP_DATA::iterator it = delMap.begin(); it != delMap.end(); ++it) {
-
MAP_DATA::iterator itDel = m_map.find(it->first);
-
if (itDel != m_map.end())
-
m_map.erase(itDel);
-
}
-
delMap.clear();
-
}
-
-
void CMapExa::Show()
-
{
-
for (MAP_DATA::iterator it = m_map.begin(); it != m_map.end(); it++)
-
{
-
cout << it->first << endl;
-
cout << it->second << endl;
-
}
-
}
-
-
int main()
-
{
-
CMapExa objMapExa;
-
objMapExa.OnInit();
-
objMapExa.DelFunCorrect();
-
//objMapExa.DelFunConfuse();
-
objMapExa.Show();
- }