Moderator edit: This response and its replies have been split from the C and C++ Timesaving Tips sticky because they do not add relevant material, and they are long enough to distract from the intended purpose of the thread. Further replies on this topic may be posted in this thread, while other useful time saving tips should still be directed to the sticky. -Narue
Well u can always use STL's "for_each" for efficiency, readability, portability & usability. Available in std::algorithm for any container types ;)
Post your tips for making life easier in C and C++. I'll start:
Standard vector object initializationThe biggest problem with the standard vector class is that one can't use an array initializer. This forces us to do something like this:
#include <iostream> #include <vector> using namespace std; int main() { vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); // Use the vector }
Anyone who's had the rule of redundancy pounded into their head knows that the previous code could be wrapped in a loop:
#include <iostream> #include <vector> using namespace std; int main() { vector<int> v; for (int i = 1; i < 6; i++) v.push_back(i); // Use the vector }
However, it's not terribly elegant, especially for a vector of complex types. So, Narue's first timesaving tip for C++ is to use a temporary array so that you can make use of an initializer. Because the vector class defines a constructor that takes a range of iterators, you can use the array to initialize your vector:
#include <iostream> #include <vector> using namespace std; int main() { int a[] = {1,2,3,4,5}; vector<int> v(a, a + 5); // Use the vector }