cocos2dx使用map容器實例(C++)

關於map容器
cocos2dx中使用map容器,頭文件無須添加,
只要聲明命名空間using namespace std;即可

關於map學習資料
學習資料1:
http://blog.csdn.net/realxie/article/details/7252662  這是一個很不錯的基礎實例!贊!
我們在cocos2dx的例如helloworld的int中添加以下兩段代碼:

 

    map<int* , int> pMap ;
    int A[100]={5,2,5,8,9};
    for(int i=0;i<100;i++){
        *(A+i) = i;
        pMap[A+i] = A[i]+1;
    }
    
    map<int*, int>::iterator it= pMap.begin();
    while(it != pMap.end())
    {
        log("%i",(*(it++)->first));
    }

可以在輸出結果,從0,到99!
PS說一下,pMap[A+i] = A[i]+1;並沒有改變數組中數據的值。


學習資料2:
http://blog.csdn.net/lijiaz5033/article/details/5202177
這個帖子更是超級贊,很完美的解釋了map的基礎用法.

我參考他的帖子,寫了一個map,是std::map<string, float> _map;

我們在cocos2dx的例如helloworld的int中添加以下代碼:

    /* define a map */
    std::map<string, float> _map;
    /* insert */
    _map.insert( std::map<string,float>::value_type("11", 32.8) );
    _map.insert( std::map<string,float>::value_type("12", 33.2) );
    _map.insert( std::map<string,float>::value_type("ss", 35.8) );
    _map.insert( std::map<string,float>::value_type("nn", 36.4) );
    _map.insert( std::map<string,float>::value_type("sss", 37.8) );
    _map.insert( std::map<string,float>::value_type("kk", 35.8) );
    
    /* 這個是常用的一種map賦值方法 */
    _map["kk2"] = 245.3;
    
    /* find by key */
    std::map<string,float>::iterator itr;
    itr = _map.find("kk");
    
    if( itr != _map.end() )
    {
        log("Item:  %s   found, content:  %f",itr->first.c_str(),itr->second);
    }
輸出結果: Item:kk  found,content:35.8
他帖子中提及到的以下幾個也很常用,不過我上面並未使用.
也寫下來,參考看一下吧.

/* delete item from map 刪除item */    
 if( itr != _map.end() )    
 {        
  _map.erase(itr);    
 }      
  /* travel through a map */  
 std::map<int,float>::iterator itr1  =  _map.begin();   
for(  ;  itr1  !=  _map.end();  ++itr1 )    
 {  
    std::cout  << "Item:"  << itr1->first << ", content: " << itr1->second << std::endl;  
 }       
 std::cout  << std::endl;        
/* empty a map  清空map*/   
 _map.clear();      



學習資料3: cocos2dx引擎的源碼 GUIReader的cpp文件

map也可以用來存放指針哦!在cocos2dx GUIReader的文件中
    std::map<std::string, Ref*> object_map = GUIReader::getInstance()->getParseObjectMap();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章