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

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

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

 /** Default constructor Map()默认构造函数*/
Map<K, V>()
: _data()
{
static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
CCLOGINFO("In the default constructor of Map!");
}
/** Constructor with capacity. 创建Map,并设置容量*/
explicit Map<K, V>(ssize_t capacity)
: _data()
{
static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
CCLOGINFO("In the constructor with capacity of Map!");
_data.reserve(capacity);
}
/** Copy constructor. 用一个已经存在的Map创建另一个Map*/
Map<K, V>(const Map<K, V>& other)
{
static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
CCLOGINFO("In the copy constructor of Map!");
_data = other._data;
addRefForAllObjects();
}
/** Move constructor. 用一个已经存在的Map创建另一个Map*/
Map<K, V>(Map<K, V>&& other)
{
static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");
CCLOGINFO("In the move constructor of Map!");
_data = std::move(other._data);
}

添加元素函数:

 /** 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以及子类指针类型*/
void insert(const K& key, V object)
{
CCASSERT(object != nullptr, "Object is nullptr!");
object->retain();
erase(key);
_data.insert(std::make_pair(key, object));
}

移除元素的函数:

 /** 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.指定位置移除对象,参数是迭代器,返回值是下一个迭代器*/
iterator erase(const_iterator position)
{
CCASSERT(position != _data.cend(), "Invalid iterator!");
position->second->release();
return _data.erase(position);
}
/** 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).通过给定键移除一个指定位置的元素*/
size_t erase(const K& k)
{
auto iter = _data.find(k);
if (iter != _data.end())
{
iter->second->release();
_data.erase(iter);
return ;
}
return ;
}
/** Removes some elements with a vector which contains keys in the map.param keys Keys of elements to be erased.通过给定建集合移除多个元素*/
void erase(const std::vector<K>& keys)
{
for(const auto &key : keys) {
this->erase(key);
}
}
/** 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.移除所有的元素*/ void clear()
{
for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)
{
iter->second->release();
}
_data.clear();
}

查找元素的函数:

 /** 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).*/
const V at(const K& key) const //通过键返回值
{
auto iter = _data.find(key);
if (iter != _data.end())
return iter->second;
return nullptr;
}
V at(const K& key) //返回指定整型键的值
{
auto iter = _data.find(key);
if (iter != _data.end())
return iter->second;
return nullptr;
}
/** 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).*/
const_iterator find(const K& key) const //查找Map容器中的对象,返回值迭代器
{
return _data.find(key);
}
iterator find(const K& key) //查找Map容器中的对象,返回值迭代器
{
return _data.find(key);
}

其他操作函数:

 ()、  std::vector<K> keys();            //返回所有的键

 ()、  std::vector<K> keys(V object);       //返回与对象匹配的所有的键值

 ()、  ssize_t size();               //返回元素的个数

实例:

.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);
}

Cocos2d-x之Map<K, V>的更多相关文章

  1. cocos基础教程(5)数据结构介绍之cocos2d::Map<K,V>

    1.概述 cocos2d::Map<K,V> 是一个内部使用了 std::unordered_map的关联容器模版. std::unordered_map 是一个存储了由key-value ...

  2. 关于jsp利用EL和struts2标签来遍历ValueStack的东东 ------> List<Map<K,V>> 以及 Map<K,<List<xxx>>> 的结构遍历

    //第一种结构Map<K,<List<xxx>>> <body> <% //显示map<String,List<Object>& ...

  3. JDK源码(1.7) -- java.util.Map<K,V>

     java.util.Map<K,V> 源码分析 --------------------------------------------------------------------- ...

  4. Map<k,v>接口

    https://docs.oracle.com/javase/8/docs/api/java/util/Map.html public interface Map<K,V> K—key,V ...

  5. 随笔1 interface Map<K,V>

    第一次写笔记就从map开始吧,如上图所示,绿色的是interface,黄色的是abstract class,蓝色的是class,可以看出所有和图相关的接口,抽象类和类的起源都是interface ma ...

  6. Mybatis返回List<Map<K,V>>

    最终映射的字段名 会被作为 hashMap 的 key , <!-- TODO 测试返回 HashMap--> <resultMap id="testResultMap&q ...

  7. Map<K, V> 中k,v如果为null就转换

    Set<String> set = map.keySet(); if(set != null && !set.isEmpty()) { for(String key : s ...

  8. Java------遍历Map<k,v>的方法

    1. public class MapAction extends ActionSupport{ private Map<String, User> map = new HashMap&l ...

  9. Cocos2d-x3.0模版容器具体解释之二:cocos2d::Map&lt;K,V&gt;

    1.概述: 版本号: v3.0 beta 语言: C++ 定义在 "COCOS2DX_ROOT/cocos/base" 路径下的 "CCMap.h" 的头文件里 ...

随机推荐

  1. 好书推荐---Python网络编程基础

    Python网络编程基础详细的介绍了网络编程的相关知识,结合python,看起来觉得很顺畅!!!

  2. php上传文件如何保证上传文件不被改变或者乱码

    很多网站上传文件都截取文件后缀,前面用时间错加后缀组成,然而一下下载的网站并不需要这样,需要保持原来的文件名,这里讲述一下 //上传操作 function uploadify(){ //var_dum ...

  3. C#中out和ref的区别

    来源:https://www.cnblogs.com/sunliyuan/p/5999045.html 首先,俩者都是按地址传递的,使用后都将改变原来参数的数值. 其次,ref可以把参数的数值传递进函 ...

  4. idea 创建 SSM + maven Java Web 项目流程

    idea 创建 SSM + maven Java Web 项目流程 一.idea 中选择File,New Project 新建项目 二.选择Maven,勾选上面的Create from archety ...

  5. UIViewController push或presentViewController 弹出方式

    //导航控制器数量 add xjz 判断是push还是present出来的 NSArray *viewcontrollers = self.navigationController.viewContr ...

  6. 03.Linux-CentOS系统user用户改密码问题

    问题:[user@localhost ~]$ passwdChanging password for user user.Changing password for user.(current) UN ...

  7. nginx部署静态资源

    第一步.推荐使用EditPlus中ftp工具 安装,然后点击File->FTP->FTPUPLOAD->Settings->add.然后进行配置: 这样只是为了方便编辑Linu ...

  8. 四、Angular新建组件和使用

    1.新建组件命令 ng component 组件路径 如果报错换成 ng generate component 组件路径 2.组件 ts 文件详解 3.组件会自动引入到app.mudule.ts里面 ...

  9. solrJ 基本使用

    添加: PropertiesUtils pro = new PropertiesUtils();String path = pro.load("solr.properties", ...

  10. Linux命令行工具之free命令

    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11524691.html 使用 free 查看整个系统的内存使用情况 Note:不同版本的free输出可 ...