Introduction to Vector (T) containers and instances in Cocos2d-x

Source: Internet
Author: User

Introduction to Vector (T) containers and instances in Cocos2d-x
Vector 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 It is a std: vector that imitates C ++. Template Class. 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. Vector The performance is better than the _ Array class, the official Coco2d-x will Vector Designed as an alternative to _ Array, Vector is recommended. Class.

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 & Other ). Create another Vector object with an existing Vector object, where & other is the reference parameter of the Left value.

Vector (Vector & 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 & 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

Below is a summary of the commonly used removal of Vector Functions of elements in the 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
 
   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 list member variable to cocos2d: Vector. , See the code 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
 
  (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 (MAX_COUNT) is to create a list member variable of the Vector type, and specify the Sprite pointer type in the memory of the Vector container. 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
 
  
: 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; // call the operator (* operator) to access the element sprite pointed to by the iterator-> 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

Related Article

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.