- // union_test.cpp : 定义控制台应用程序的入口点。
- //
- /*
- 结论:
- typedef std::map<int, desktop*> deskMap; 存放的是指针,也就是到时候指针指向的内存如果改变,则结果也改变
- typedef std::map<int, desktop> deskMap2; //存放的是数据,
- */
- #include "stdafx.h"
- #include <map>
- #include <iostream>
- typedef struct _desk{
- int legs;
- int id;
- }desktop;
- /* 注意值一个是存指针,一个是存数据 */
- typedef std::map<int, desktop*> deskMap;
- typedef std::map<int, desktop> deskMap2;
- using namespace std;
- /*结果
- 024
- 124
- 224
- */
- void no_malloc_test()
- {
- deskMap map;
- deskMap::iterator iter;
- desktop desk, *p;
- int i;
- for (i = 0; i < 3; i++)
- {
- desk.id = i;
- desk.legs = i * i;
- map.insert(deskMap::value_type(i, &desk));
- }
- for (iter = map.begin(); iter != map.end(); iter++)
- {
- p = iter->second;
- cout << iter->first << p->id << p->legs <<endl;
- }
- map.clear();
- }
- /*
- 结果:
- 000
- 111
- 224
- */
- void no_malloc_test2()
- {
- deskMap2 map;
- deskMap2::iterator iter;
- desktop desk, *p;
- int i;
- for (i = 0; i < 3; i++)
- {
- desk.id = i;
- desk.legs = i * i;
- map.insert(deskMap2::value_type(i, desk));
- }
- for (iter = map.begin(); iter != map.end(); iter++)
- {
- p = (desktop*)&iter->second;
- cout << iter->first << p->id << p->legs <<endl;
- }
- map.clear();
- }
- /*
- 结果:改变的值会保存
- 000
- 111
- 224
- 010
- 121
- 234
- */
- void no_malloc_modify_test2()
- {
- deskMap2 map;
- deskMap2::iterator iter;
- desktop desk, *p;
- int i;
- for (i = 0; i < 3; i++)
- {
- desk.id = i;
- desk.legs = i * i;
- map.insert(deskMap2::value_type(i, desk));
- }
- for (iter = map.begin(); iter != map.end(); iter++)
- {
- p = (desktop*)&iter->second;
- cout << iter->first << p->id << p->legs <<endl;
- p->id++;//modify
- }
- for (iter = map.begin(); iter != map.end(); iter++)
- {
- p = (desktop*)&iter->second;
- cout << iter->first << p->id << p->legs <<endl;
- }
- map.clear();
- }
- void new_test()
- {
- deskMap map;
- deskMap::iterator iter;
- desktop *p;
- desktop *pdesk1 = new desktop;
- desktop *pdesk2 = new desktop;
- desktop *pdesk3 = new desktop;
- pdesk1->id = 0;
- pdesk1->legs = 0;
- pdesk2->id = 1;
- pdesk2->legs = 1;
- pdesk3->id = 2;
- pdesk3->legs = 4;
- map.insert(deskMap::value_type(1, pdesk1));
- map.insert(deskMap::value_type(2, pdesk2));
- map.insert(deskMap::value_type(3, pdesk3));
-
- /* 删除pdesk1, 输出结果如下。也就是指向同一块内存*/
- //delete pdesk1;
- #if 0
- 1-572662307-572662307
- 211
- 324
- #endif
-
- for (iter = map.begin(); iter != map.end(); iter++)
- {
- p = iter->second;
- cout << iter->first << p->id << p->legs <<endl;
- }
- map.clear();
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- no_malloc_modify_test2();
- return 0;
- }
09-05 12:39