C++ 编程规则 使用范例

5630阅读 0评论2019-06-27 iibull
分类:Windows平台

头文件的顺序. 
  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成员函数   

点击(此处)折叠或打开  迭代器的使用范例.

  1. #include <iostream>
  2. #include <map>
  3. using namespace std;

  4. class CMapExa
  5. {
  6. public:
  7.   void OnInit();
  8.   void DelFunConfuse();
  9.   void DelFunCorrect();
  10.   void Show();
  11. private:
  12.   typedef map<int, int> MAP_DATA;
  13.   MAP_DATA m_map;
  14. };

  15. void CMapExa::OnInit()
  16. {
  17.   m_map.insert(MAP_DATA::value_type(1,1));
  18.   m_map.insert(MAP_DATA::value_type(2,2));
  19.   m_map.insert(MAP_DATA::value_type(3,3));
  20. }

  21. void CMapExa::DelFunConfuse() //不好的方式
  22. {
  23.   for (MAP_DATA::iterator it = m_map.begin(); it != m_map.end();)
  24.   {
  25.     m_map.erase(it++); //容易错误使用为 m_map.erase(it);
  26.   }
  27. }

  28. void CMapExa::DelFunCorrect() //建议的方式
  29. {
  30.   MAP_DATA delMap;
  31.   for (MAP_DATA::iterator it = m_map.begin(); it != m_map.end(); ++it) {
  32.     delMap[it->first] = it->second;
  33.   }

  34.   for (MAP_DATA::iterator it = delMap.begin(); it != delMap.end(); ++it) {
  35.     MAP_DATA::iterator itDel = m_map.find(it->first);
  36.     if (itDel != m_map.end())
  37.       m_map.erase(itDel);
  38.   }
  39.   delMap.clear();
  40. }

  41. void CMapExa::Show()
  42. {
  43.   for (MAP_DATA::iterator it = m_map.begin(); it != m_map.end(); it++)
  44.   {
  45.      cout << it->first << endl;
  46.      cout << it->second << endl;
  47.   }
  48. }

  49. int main()
  50. {
  51.   CMapExa objMapExa;
  52.   objMapExa.OnInit();
  53.   objMapExa.DelFunCorrect();
  54.   //objMapExa.DelFunConfuse();
  55.   objMapExa.Show();
  56. }






上一篇:C++ 编程规则 类
下一篇:C++ STL 基础