Inserting into a sorted std::vector
MyVec.push_back(MyInt)
if (MyVec.size() > 1)
{
  std::inplace_merge(
    MyVec.begin(), 
    MyVec.begin() + (MyVec.size() - 2), 
    MyVec.End());
}
This won't be the fastest way of performing an insert, but it will probably be the smallest amount of code. For the fastest way, look at finding with a binary search, then inserting.
Disclaimer: If you are going to be inserting many things into the middle of a vector, you probably shouldn't be using a vector. A list would be more suited.
Constructor variable initialisation order
This is a subtle C++ism that I forgot about and caught me out today.
When initialising items in a constructor's initialisation list, the order of initialisation is dependant on the order the variables appear in the class definition, not the initialisation list.
An example will help:
class MyClass
{
  MyClass();
  int a;
  int b;
  int c;
};
MyClass::MyClass() :
  b(0), c(0), a(0)
{
}
In the above example, a, will be initialised first followed by b, then c.
 
 
 
 Posts
Posts
 
 
2 comments:
These are very helpful tips on C++ programming. Thanks for sharing a very informative article.
Hi thhanks for sharing this
Post a Comment