RSS Forums RSS
Please support our C++ advertiser: Programming Forums

Response to time saving tips sticky

Join Date: May 2005
Posts: 7
Reputation: bsrivastava is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 1
bsrivastava bsrivastava is offline Offline
Newbie Poster

Re: C and C++ Timesaving Tips

  #1  
May 9th, 2005
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



Originally Posted by Narue
Post your tips for making life easier in C and C++. I'll start:


Standard vector object initialization

The 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
}
AddThis Social Bookmark Button
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 1:13 pm.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC