網頁

2013年5月24日 星期五

C++ Map 操作

Last Update: 2013/05/24 17:43+08
Type: Note


Content


前置
#include "stdafx.h"
#include <string>
#include <map>
using namespace std;


宣告
int _tmain(int argc, _TCHAR* argv[])
{
 map<string, int> maps;
Insert
 map<string,int>::iterator it = maps.begin();
 maps.insert(it, pair<string,int>("A",26));
 maps.insert(it, pair<string,int>("B",27));
 maps.insert(it, pair<string,int>("C",28));
 maps.insert(it, pair<string,int>("D",29));
 maps["E"] = 30;
For Loop
 for (it=maps.begin(); it != maps.end(); ++it){
  printf("%s = %i\n", it->first.c_str(), it->second);
 }
Get
 printf("E = %i\n", maps["E"]);
 printf("F = %i\n", maps["F"]);//預設為0
Remove
 maps.erase("E");
Find
 it = maps.find("E");
 if(it == maps.end())
  printf("not found.\n");
 else
  printf("%s = %i\n", it->first.c_str(), it->second);
The end...
    
 getchar();
 return 0;
}

2013年5月10日 星期五

C++ Macro Note

Last Update: 2013/05/11 21:33+08
Type: Note

Intro

C++ Macro 筆記
#define GetObjName(x) #x
#define DebugPrint(msg) printf("%s ; %s ; %s ; %d\n", #msg, __FILE__, __FUNCTION__, __LINE__)
#define Contact(x, y) x##y


int _tmain(int argc, _TCHAR* argv[])
{

 printf("line: %d \n", __LINE__);
 printf("file: %s \n", __FILE__);
 printf("function: %s \n", __FUNCTION__);
 //printf("function: %s \n", __func__);
 printf("time: %s \n", __TIME__);
 printf("date: %s \n", __DATE__);
 //printf("STDC: %d \n", __STDC__);
 //printf("STDC_HOSTED: %d \n", __STDC_HOSTED__);
 //printf("VERSION: %s \n", __VERSION__);
 printf("TIMESTAMP: %s \n", __TIMESTAMP__);


 char* s = GetObjName(MyClass);
 printf("%s \n", s);
 Contact(pri, ntf) ("exec printf \n");
 DebugPrint("Debug");


 getchar();
 return 0;
}
Macro中的# 代表取得variable名稱
該變數可以是 class, function, ...

## 是將2個變數粘在一起, pri##ntf = printf

__FILE__ , __FUNCTION__, __LINE__, ... 是 Compiler 預先就定義好的變數
debug時, 可以print出來, 方便識別


C++ operator new/delete

Last Update: 2013/05/10 17:50+08


Intro

Operator new/delete 的測試
先說明一下 new 和 delete 的行為, 如下
MyClass* test = new MyClass();
/*Operator new(sizeof(MyClass)) => exec constructor*/
delete test
/*exec destructor => free(test)*/

2013年5月3日 星期五

C++ new class or not

Last Update: 2013/05/03 18:39+08


Intro

關於使用Class時, 要不要 "new" 一個出來
本來以為C++的memory都要自己管理
沒想到也有交給別人的時候...
嘛 是我太弱了

就是下面2行的差異
MyClass temp1;
MyClass *temp2 = new MyClass();