Introduction to vector <t> containers and instances in Cocos2d-x

Source: Internet
Author: User

Vector <t> is Cocos2d-x 3. X releases the list container, so what it can hold is the object pointer created by REF and subclass, where T is the template, indicating the type that can be put into the container, in the Cocos2d-x 3. in x, t indicates the ref class. Vector <t> is designed to imitate the STD: vector <t> template class of C ++. In terms of memory management, the reference count of _ array is not used, and its memory management is automatically handled by the compiler. You do not need to consider the memory release issue. The performance of vector <t> is better than the _ array class. The Coco2d-x officially designs vector <t> as a substitute of _ array, and the vector <t> class is recommended.

 

1. Create a vector object

There are many functions to create a vector object. The following is a summary of common functions:

Vector (). Default constructor.

Vector (ssize_t capacity ). Create a vector object and set the capacity.

Vector (const vector <t> & other ). Create another vector object with an existing vector object, where & other is the reference parameter of the Left value.

Vector (vector <t> & other ). Create another vector object with an existing vector object, where & other is the right value reference parameter.

 

Is the left and right values displayed? All expressions and variables in C ++ are either left or right. The left value is a non-temporary variable that can be used in multiple statements. The right value refers to temporary variables, which are valid only in the current statement. For example, in the statement int I = 0;, I is the left value and 0 is the right value. The left and right values can also appear in the function parameter list, that is, the left value reference (&) and right value reference (&), as shown in the following code.

Void process_value (Int & I) {// & I indicates the left value reference

STD: cout <"Left reference:" <I <STD: Endl;

}

 

Void process_value (Int & I) {// & I indicates the right value reference

STD: cout <"right value reference:" <I <STD: Endl;

}

 

Int main (){

Int A = 0;

Process_value (a); // call the void process_value (Int & I) Function

Process_value (1); // call the void process_value (Int & I) Function

}

 

2. Add Elements

Adding elements to a vector object must be of the ref object pointer type. The following is a summary of common functions:

Void pushback (t object ). Add an element. t indicates the ref object pointer type.

Void pushback (const vector <t> & other ). Add all elements in a vector object to the current vector object.

Void insert (ssize_t index, t object ). Insert an element at the specified position. ssize_t is an alias of the int type.

 

3. Remove Elements

The following is a summary of common functions for removing elements from a vector <t> container:

Void popback (). Remove the last element.

Void eraseobject (t object, bool removeall = false ). Removes an element.

Iterator erase (iterator position ). The object is removed at the specified position. The parameter is the iterator, And the return value is the next iterator.

Iterator erase (iterator first, iterator last ). Specifies the range of objects to be removed (first ~ Last), the parameter is the iterator, And the return value is the next iterator.

Iterator erase (ssize_t index ). Removes the element of a specified index. The parameter is ssize_t, And the return value is the next iterator.

Void clear (). Remove all elements.

 

4. Replacing and exchanging Elements

We can also use the following function to replace and exchange elements in a vector container:

Void swap (T object1, t object2 ). Exchange two elements.

Void swap (ssize_t index1, ssize_t index2 ). Swap two specified position elements.

Void Replace (ssize_t index, t object ). Replaces the specified position element with an object.

 

5. Search operations

We sometimes need to operate the elements in the vector. Below is a summary of common search functions:

Iterator find (t object ). Search for objects in the vector container and return value iterator.

T At (ssize_t index ). Returns the elements in the vector container Based on the index position.

T front (). Returns the first element.

T back (). Returns the last element.

T getrandomobject (). Returns a random element.

Bool contains (t object ). Returns whether an element exists in the container.

Ssize_t getindex (t object ). Returns the location of the specified object.

 

6. Other operation functions

In addition, there are many vector object functions. Below is a summary of common functions:

Ssize_t size (). Returns the number of elements.

Ssize_t capacity (). Returns the vector capacity.

 

Instance: vector container

To get familiar with the main functions of the Vector class, we will implement the example in section 13.2.2 through the vector list container. For the scenario shown in 13-3, click go in the lower-right corner to add 100 genie to the scenario.

Let's take a look at the code section. The helloworldscene. H code is as follows:

#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__

The above code is compared with the instance in section 13.2.2. We changed the type of the List member variable to cocos2d: vector <cocos2d: SPRITE *>, as shown in line ①. Note that we no longer need to declare the destructor. It is easier to use the vector to manage the system automatically processed by the compiler in memory.

The main code in helloworldscene. cpp is as follows:

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

Line ① Of the above Code this-> List = vector <sprite *> (max_count) is to create a list member variable of the vector type, and specify that the vector container memory is placed in the sprite pointer type, the vector constructor parameter is the initial capacity of the container. The second line of code is used to create 100 genie objects in a for loop. Line ③ code this-> list. pushback (sprite) is used to add the sprite object to the list container object. pushback is an element function used by the vector to add elements. Because the template of the List container is set as the sprite pointer in row ①, so the pushback function can only let go the sprite and its subclass pointer type.

Line 4 code for (const Auto & sprite: This-> List ){...} Is to traverse the list container objects cyclically. Here, the loop is the new function of the C ++ 11 standard, range-based for loops, and range-based for loops is translated as "sequential for loop statement ", the for loop statement allows repeated traversal of a set of sequences, which can be any repeated traversal sequence. All C ++ standard container data containers can be used as such sequences. The declared reference type (Auto &) in for can be easily modified in the loop body, and declared as const Auto & can improve the execution efficiency.

 

It is prompted that you can use the C ++ iterator to traverse the vector container. See the code below. The related begin () and end () functions are defined in vector.

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);}
More content please pay attention to the first domestic Cocos2d-x 3.2 version of the book "Cocos2d-x practice: C ++ volume" book exchange discussion site: http://www.c Ocoagame.net
For more exciting video courses, please follow the Cocos course in Zhijie class: http: // v.51w Ork6.com
Welcome to the Cocos2d-x Technology Discussion Group: 257760386 welcome to the knowledge of the IOS classroom public platform

Introduction to vector <t> containers and instances in Cocos2d-x

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.