Cocos2d-x 3.0数据结构——cocos2d::Map
模版参数注意:使用现代的c++,本地存储对象比堆存储对象好。所以请不要用new操作来分配 警告: 示例警告:cocos2d::Map //create Map<K,V> with default size and add a sprite into it
auto sp0 = Sprite::create();
sp0->setTag(0);
Map<std::string,Sprite*> map0;
std::string mapKey0 = "MAP_KEY_0";
map0.insert(mapKey0,sp0);
log("The size of map is %zd.",map0.size());
//create a Map<K,V> with capacity equals 5
Map<std::string,Sprite*> map1(map0);
std::string mapKey1 = "MAP_KEY_1";
if(!map1.empty()){
auto spTemp = (Sprite*)map1.at(mapKey0);
log("sprite tag = %d",spTemp->getTag());
auto sp1 = Sprite::create();
sp1->setTag(1);
map1.insert(mapKey1,sp1);
//get all keys,stored in std::vector,that matches the object
std::vector<std::string> mapKeyVec;
mapKeyVec = map1.keys();
for(auto key : mapKeyVec)
{
auto spTag = map1.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(),map1.bucket(key));
}
log("%zd buckets in the Map container",map1.bucketCount());
log("%zd element in bucket 1",map1.bucketSize(1));
//get a random object if the map isn't empty,otherwise it returns nullptr
log("The random object tag = %d",map1.getRandomObject()->getTag());
//find(const K& key) can be used to search the container for an element with 'key'
//erase(const_iterator position) remove an element with an iterator
log("Before remove sp0,size of map is %zd.",map1.size());
map1.erase(map1.find(mapKey0));
log("After remove sp0,map1.size());
}
//create a Map<K,Sprite*> map2(5);
map2.reserve(10); //set capacity of the map
运行结果:
最佳用法类似 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |