cocos2d-x中级知识(一)——数据容器类

来源:互联网 发布:python 高级用法 编辑:程序博客网 时间:2024/06/04 17:47

综述

cocos2d-x容器类可分为两大类:列表和字典

列表字典包括_Array、Vector<T>、和ValueVector

字典容器包括_Dictionary,Map<K,V>、ValueMap和ValueMapIntKey

其中,Vector<T>,Map<K,V>是3.x推崇的容器类,类似于C++的标准容器类std::vector<T> 和 std::unordered_map<K,V>

cocos2d-x根类Ref

Ref在2.x时是CCObject类,是大部分对象的基类

包装类Value

value可以将int,float,double,bool,unsigned char 和 char*等基本数据类型包装成类,Value类所有的构造函数如下:
 Value ()  Value (unsigned char v)  Value (int v)  Value (float v)  Value (double v)  Value (bool v)  Value (const char *v)  Value (const std::string &v)  Value (const ValueVector &v)  Value (ValueVector &&v)  Value (const ValueMap &v)  Value (ValueMap &&v)  Value (const ValueMapIntKey &v)  Value (ValueMapIntKey &&v)  Value (const Value &other)  Value (Value &&other)  ~Value ()

用法如下:
Value val;   // 调用默认构造函数if (val.isNull()) {    log("val is null");}else{    std::string str =val.getDescription();    log("The description of val0:%s",str.c_str());}//----------------------------------------------------Value val1(65);   // 用一个 int 初始化//Value val1(3.4f);   // 用一个 float 初始化//Value val1(3.5);   // 用一个 double 初始化log("The description of the integer value:%s",val1.getDescription().c_str());log("val1.asByte() = %c",val1.asByte());//----------------------------------------------------std::string strV = "string";Value val2(strV);   // 用 string 初始化log("The description of the string value:%s",val2.getDescription().c_str());//----------------------------------------------------auto sp0 = Sprite::create();Vector<Object*>* vecV = new Vector<Object*>();vecV->pushBack(sp0);Value val3(vecV);   // 用 Vector 初始化log("The description of the Vector value:%s",val3.getDescription().c_str());delete vecV;//----------------------------------------------------Map<std::string, Object*>* mapV = new Map<std::string, Object*>();mapV->insert(strV,sp0);Value val4(mapV);   // 用 Map 初始化log("The description of the Map value:%s",val4.getDescription().c_str());delete mapV;//----------------------------------------------------Value val6(&val4);   // 用 Map 初始化log("The description of the Value-type value:%s",val6.getDescription().c_str());//----------------------------------------------------val2 = val1;   // 在两个不同指类型间赋值log("operator-> The description of val2:%s",val2.getDescription().c_str());val2 = 4;   // 直接赋值log("operator-> The description of val4:%s",val2.getDescription().c_str());

输出如下

cocos2d: val is nullcocos2d: The description of the integer value:65 cocos2d: val1.asByte() = Acocos2d: The description of the string value:string cocos2d: The description of the Vector value:true cocos2d: The description of the Map value:true cocos2d: The description of the Value-type value:true cocos2d: operator-> The description of val2:65 cocos2d: operator-> The description of val4:4

Ref列表容器

_Array和Vector<T>,_Array在cocos2dx2.0时代就是CCArray类,建议使用Vector<T>

Vector<T>容器

1,创建Vector对象函数
(1)Vector()。默认的构造函数
(2)Vector(ssize_t capacity)。创建Vector对象,并设置容量
(3)Vector(const Vector<T>&other)。用一个已经存在的Vector对象创建另一个Vector对象,其中&other是左值引用参数传递。
(4)Vector(Vector<T>&&other)用一个已经存在的Vectore对象创建另一个Vector对象,其中&&other是右值引用参数传递。
提示  左值与右值?C++中所有的表达式和变量要么是左值,要么是右值。左值的定义就是非临时变量,可以在多条语句中使用的变量。右值是指临时的变量,它们只在当前的语句中有效。例如在语句int i = 0;中i为左值,0右值。左值与右值还可以出现在函数参数列表中,左值引用(&)和右值引用(&&),如下代码所示。
void process_value(int& i) {  //& i表示左值引用  std::cout << "左值引用: " << i << std::endl; }  void process_value(int&& i) {   //&& i表示右值引用  std::cout << "右值引用: " << i << std::endl; }  int main() {   int a = 0;   process_value(a);  //调用void process_value(int& i)函数  process_value(1);  //调用void process_value(int&& i)函数}
2,添加元素
(1)void pushBack(T object)。添加一个元素,T表示Ref对象指针类型。
(2)void pushBack(const Vector<T>&other)。把一个Vector对象中所有元素添加到当前Vector对象中。
(3)void insert(ssize_t index,T object)。在指定位置插入元素,ssize_t是int类型别名。
3,移除元素
(1)void popBack()。移除最后一个元素
(2)void eraseObject(T object,bool removeAll=false)。移除某个元素
(3)iterator erase(iterator position)。指定位置移除对象,参数是迭代器,而返回值是下一个迭代器。
(4)iterator erase(iterator first,iterator last)。指定移除对象范围(first~last),参数是迭代器,而返回值是下一个迭代器。
(5)iterator earse(ssize_t index)。移除一个指定索引的元素,参数是ssize_t,而返回值是下一个迭代器。
4,替换和交换元素
(1)void swap(T object1,Tobject2)。交换两个元素。
(2)void swap(ssize_t index1,ssize_t index2)。交换两个指定位置元素。
(3)void replace(ssize_t index,T object)。用一个对象替代指定位置元素。
5,查找操作
(1)iterator find(T object) 查找Vector容器中的对象,返回值迭代器。
(2)T at(ssize_t,index)。根据索引位置返回Vector容器中的元素。
(3)T front()。返回第一个元素。
(4)T back()。返回最后一个元素。
(5)T getRandomObject()。返回随机元素。
(6)bool contains(T object)。返回某个元素是否存在容器中。
(7)ssize_t getIndex(T object)。返回指定对象的位置。
6,其他操作函数
(1)ssize_t size()。返回元素个数。
(2)ssize_t capacity()。返回Vector的容量。

实例:Vector容器

为了熟悉Vector类的主要函数,下面我们将13.2.2一节的实例通过Vector列表容器实现一下。如图13-3所示场景,点击右下角的Go按钮,在场景中添加100个精灵。
下面我们看看代码部分,HelloWorldScene.h代码如下:
#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" #define MAX_COUNT 100 class HelloWorld : public cocos2d::Layer{cocos2d::Vector<cocos2d::Sprite*> list;  ①public:    static cocos2d::Scene* createScene();     virtual bool init();          void menuCloseCallback(cocos2d::Ref* pSender);        CREATE_FUNC(HelloWorld);}; #endif // __HELLOWORLD_SCENE_H__

//HelloWorld.cpp
bool HelloWorld::init(){if ( !Layer::init() ){return false;} Size visibleSize = Director::getInstance()->getVisibleSize();Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto goItem = MenuItemImage::create("go-down.png","go-up.png",CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); goItem->setPosition(Vec2(origin.x + visibleSize.width - goItem->getContentSize().width/2 ,origin.y + goItem->getContentSize().height/2)); auto menu = Menu::create(goItem, NULL);menu->setPosition(Vec2::ZERO);this->addChild(menu, 1); this->list = Vector<Sprite*>(MAX_COUNT);① for(int i = 0;i < MAX_COUNT; ++i){②Sprite* sprite = Sprite::create("Ball.png");this->list.pushBack(sprite);③} return true;}  void HelloWorld::menuCloseCallback(Ref* pSender){Ref* obj = nullptr;log("List count = %d",this->list.size());Size visibleSize = Director::getInstance()->getVisibleSize(); for(const auto& sprite : this->list)④{int x = CCRANDOM_0_1() * visibleSize.width;int y = CCRANDOM_0_1() * visibleSize.height; sprite->setPosition( Vec2(x, y) );this->removeChild(sprite);this->addChild(sprite);} }


上述代码第①行this->list = Vector<Sprite*>(MAX_COUNT)是创建Vector 类型的list成员变量,并指定Vector容器内存放的是Sprite指针类型,Vector构造函数参数是容器的初始化容量。第②行代码进行for循环创建100个精灵对象。第③行代码this->list.pushBack(sprite)是将精灵对象添加到list容器对象中,pushBackVector通过的添加元素函数,由于在第①行设置list容器的模板为Sprite指针,所以pushBack函数只能放过Sprite和其子类指针类型
第④行代码for(const auto& sprite : this->list){…}是循环遍历list容器对象,这里使用的循环是C++11规范的新功能range-based for loops,range-based for loops被翻译为“序列for循环语句”,序列for循环语句允许重复遍历一组序列,而这组序列可以是任何可以重复遍历的序列,所有C++标准容器数据容器都可用作这种序列。for中声明引用类型(auto&)可以便于在循环体中修改元素,声明为const auto&可以提高执行的效率。 提示  在遍历Vector容器时候还可以使用C++中迭代器进行遍历,参看代码如下。Vector中定义了相关的begin()end()函数

for (Vector<Sprite*>::const_iterator it = this->list.begin(); it != this->list.end(); ++it){int x = CCRANDOM_0_1() * visibleSize.width;int y = CCRANDOM_0_1() * visibleSize.height;Sprite* sprite = *it;//解引用操作符(*操作符)来访问迭代器所指向元素 sprite->setPosition( Vec2(x, y) );this->removeChild(sprite);this->addChild(sprite);}



0 0
原创粉丝点击