Cocos2d-x 3.x Migration – C++11 Subtle Mistakes

I’ll probably repeat myself that c++11 makes developing in c++ much more pleasant. However, there are some interesting issues when migrating from various class structures to the new std:: template containers and algorithms.

std::remove removes all elements of a given type, not just the first one found. Normally I try and use the for (auto& element : arr ), but in these cases I use the full iterator syntax instead. Could also use an index based loop, or no doubt another approach which I haven’t learned.

// v is vector<string> may contain duplicate strings
for ( auto& el : v ) {
    // tried to use remove, but removes all found elements
    v.erase(std::remove(v.begin(), v.end(), el), v.end()); 
}

// instead use iterator pointer
for ( auto it = v.begin(); it != v.end(); it++ )
{
  std::string element = (*it);
  if(element == "string to match")
  {
     // want to remove first string match
     v.erase(it); // iterator is invalid afterward
     break;
   }
}

[I’ll continue to append new issues as they’re encountered]

Leave a Reply

Your email address will not be published. Required fields are marked *

*