Cocos2d-x之Map<K, V>

|   版权声明:本文为博主原创文章,未经博主允许不得转载。

  Map<K, V>是Cocos2d-x 3.0x中推出的字典容器,它也能容纳Ref类型。Map<K,V>是模仿C++标准库的std::unorder_map<K, V>模板设计的。

 

创建Map<K,V>对象函数:

 1 /** Default constructor Map()默认构造函数*/
 2     Map<K, V>()
 3     : _data()
 4     {
 5         static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
 6         CCLOGINFO("In the default constructor of Map!");
 7     }
 8 /** Constructor with capacity. 创建Map,并设置容量*/
 9     explicit Map<K, V>(ssize_t capacity)
10     : _data()
11     {
12         static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
13         CCLOGINFO("In the constructor with capacity of Map!");
14         _data.reserve(capacity);
15     }
16 /** Copy constructor. 用一个已经存在的Map创建另一个Map*/
17     Map<K, V>(const Map<K, V>& other)
18     {
19         static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
20         CCLOGINFO("In the copy constructor of Map!");
21         _data = other._data;
22         addRefForAllObjects();
23     }
24 /** Move constructor. 用一个已经存在的Map创建另一个Map*/
25     Map<K, V>(Map<K, V>&& other)
26     {
27         static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
28         CCLOGINFO("In the move constructor of Map!");
29         _data = std::move(other._data);
30     }
View Code

添加元素函数:

1 /** Inserts new elements in the map. @note If the container has already contained the key, this function will erase the old pair(key, object)  and insert the new pair.param key The key to be inserted.param object The object to be inserted.在Map中添加一个新元素,V必须是Ref以及子类指针类型*/
2     void insert(const K& key, V object)
3     {
4         CCASSERT(object != nullptr, "Object is nullptr!");
5         object->retain();
6         erase(key);
7         _data.insert(std::make_pair(key, object));
8     }
View Code

移除元素的函数:

 1 /** Removes an element with an iterator from the Map<K, V> container.param position Iterator pointing to a single element to be removed from the Map<K, V>.Member type const_iterator is a forward iterator type.指定位置移除对象,参数是迭代器,返回值是下一个迭代器*/
 2     iterator erase(const_iterator position)
 3     {
 4         CCASSERT(position != _data.cend(), "Invalid iterator!");
 5         position->second->release();
 6         return _data.erase(position);
 7     }
 8 /** Removes an element with an iterator from the Map<K, V> container.param k Key of the element to be erased.Member type 'K' is the type of the keys for the elements in the container,defined in Map<K, V> as an alias of its first template parameter (Key).通过给定键移除一个指定位置的元素*/
 9     size_t erase(const K& k)
10     {
11         auto iter = _data.find(k);
12         if (iter != _data.end())
13         {
14             iter->second->release();
15             _data.erase(iter);
16             return 1;
17         }
18         return 0;
19     }  
20 /** Removes some elements with a vector which contains keys in the map.param keys Keys of elements to be erased.通过给定建集合移除多个元素*/
21     void erase(const std::vector<K>& keys)
22     {
23         for(const auto &key : keys) {
24             this->erase(key);
25         }
26     }
27 /**  All the elements in the Map<K,V> container are dropped:their reference count will be decreased, and they are removed from the container,leaving it with a size of 0.移除所有的元素*/
28 
29     void clear()
30     {
31         for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)
32         {
33             iter->second->release();
34         }
35         _data.clear();
36     }
View Code

查找元素的函数:

 1 /** Returns a reference to the mapped value of the element with key k in the map.note If key does not match the key of any element in the container, the function return nullptr.param key Key value of the element whose mapped value is accessed.Member type K is the keys for the elements in the container. defined in Map<K, V> as an alias of its first template parameter (Key).*/
 2     const V at(const K& key) const            //通过键返回值
 3     {
 4         auto iter = _data.find(key);
 5         if (iter != _data.end())
 6             return iter->second;
 7         return nullptr;
 8     }  
 9     V at(const K& key)                        //返回指定整型键的值
10     {
11         auto iter = _data.find(key);
12         if (iter != _data.end())
13             return iter->second;
14         return nullptr;
15     }
16 /** Searches the container for an element with 'key' as key and returns an iterator to it if found,otherwise it returns an iterator to Map<K, V>::end (the element past the end of the container).param key Key to be searched for.Member type 'K' is the type of the keys for the elements in the container,defined in Map<K, V> as an alias of its first template parameter (Key).*/
17     const_iterator find(const K& key) const             //查找Map容器中的对象,返回值迭代器
18     {
19         return _data.find(key);
20     }
21     iterator find(const K& key)              //查找Map容器中的对象,返回值迭代器
22     {
23         return _data.find(key);
24     }
View Code

其他操作函数:

11)、  std::vector<K> keys();            //返回所有的键
2 
32)、  std::vector<K> keys(V object);       //返回与对象匹配的所有的键值
4 
53)、  ssize_t size();               //返回元素的个数
View Code

 

实例:

.h files 

#ifndef _MAPTEST_SCENE_H_
#define _MAPTEST_SCENE_H_
#include "cocos2d.h"
class mapTest : public cocos2d::Layer
{
private:
public:
        static cocos2d::Scene* createScene();
        virtual bool init();
        void testMap();
        CREATE_FUNC(mapTest);
};
#endif // _MAPTEST_SCENE_H_

.cpp files

#include "MapTest.h"
USING_NS_CC;
Scene* mapTest::createScene()
{
        // 'scene' is an autorelease object
        auto scene = Scene::create();
        // 'layer' is an autorelease object
        auto layer = mapTest::create();
        // add layer as a child to scene
        scene->addChild(layer);
        // return the scene
        return scene;
}

// on "init" you need to initialize your instance
bool mapTest::init()
{
        {
               return false;
        }
        testMap();
        return true;
}

void mapTest::testMap()
{
        //1. 插入值
        auto sp1 = Sprite::create();
        sp1->setTag(0);
        Map<std::string, Sprite*> map1;
        std::string mapKey1 = "MAP_KEY_1";
        map1.insert(mapKey1, sp1);
        log("The size of map is %zd.", map1.size());

        //2. 使用map1创建
        Map<std::string, Sprite*>map2(map1);
        std::string mapKey2 = "MAP_KEY_2";

        //3. 判断是否为空
        if (!map2.empty())
        {
               //根据key获得值
               auto spTemp = (Sprite*)map2.at(mapKey1);
               //获得sprite的tag
               log("sprite tag = %d", spTemp->getTag());
               //创建sprite
               auto sp2 = Sprite::create();
               //设置Tag
               sp2->setTag(2);
               //插入
               map2.insert(mapKey2, sp2);
               //key集合
               std::vector<std::string>mapKeyVec;
               //遍历key
               for (auto key : mapKeyVec)
               {
                       //根据key获得value
                       auto spTag = map2.at(key)->getTag();
                       log("The sprite tag = %d, Map key = %s", spTag, key.c_str());
                       log("Element with key %s is located in bucket %zd", key.c_str(), map2.bucket(key));
               }
               log("%zd buckets in the Map container", map2.bucketSize(2));
               log("%zd element in bucket 1", map2.getRandomObject()->getTag());

               //大小
               log("Before remove sp1,size of map is %zd.", map1.size());
               //查找并删除
               map1.erase(map1.find(mapKey1));
               log("After remove sp0,size of map is %zd.", map1.size());
        }


        //5. 重新设置Map的大小
        Map<std::string, Sprite*>map3(5);
        map3.reserve(10);
}

原文地址:https://www.cnblogs.com/geore/p/5799414.html