943,902 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 89440
  • C++ RSS
You are currently viewing page 1 of this multi-page discussion thread
Mar 10th, 2005
2

C and C++ Timesaving Tips

Expand Post »
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:
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. vector<int> v;
  9.  
  10. v.push_back(1);
  11. v.push_back(2);
  12. v.push_back(3);
  13. v.push_back(4);
  14. v.push_back(5);
  15.  
  16. // Use the vector
  17. }
Anyone who's had the rule of redundancy pounded into their head knows that the previous code could be wrapped in a loop:
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. vector<int> v;
  9.  
  10. for (int i = 1; i < 6; i++)
  11. v.push_back(i);
  12.  
  13. // Use the vector
  14. }
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:
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. int a[] = {1,2,3,4,5};
  9. vector<int> v(a, a + 5);
  10.  
  11. // Use the vector
  12. }
Similar Threads
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Mar 10th, 2005
0

Re: C and C++ Timesaving Tips

One of my favorite discoveries in C++ regards displaying such a list.

Initially one might do this.
#include <iostream>
#include <vector>

using namespace std;

int main()
{
  int a[] = {1,2,3,4,5};
  vector<int> v(a, a + 5);

  for (int i = 0; i < 5; ++i)
  {
     cout << v[i] << endl;
  }
}
Or perhaps even this.
#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

int main()
{
  int a[] = {1,2,3,4,5};
  vector<int> v(a, a + 5);

  vector<int>::const_iterator it, end = v.end();
  for (it = v.begin(); it != end; ++it)
  {
     cout << *it << endl;
  }
}
But I happend upon the following that can make things even easier.
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

using namespace std;

int main()
{
  int a[] = {1,2,3,4,5};
  vector<int> v(a, a + 5);

  copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\n"));
}
The output for all of these is merely this.
Quote ...
1
2
3
4
5
Last edited by Dave Sinkula; Oct 14th, 2005 at 1:23 pm. Reason: Fixed iterator loop condition -- thanks Micko.
Team Colleague
Reputation Points: 2780
Solved Threads: 312
long time no c
Dave Sinkula is offline Offline
4,790 posts
since Apr 2004
Mar 11th, 2005
0

Re: C and C++ Timesaving Tips

From the code snippet on the very same subject is another way to initialize a vector ...

C++ Syntax (Toggle Plain Text)
  1. // another way to load a vector ...
  2. vector<char> cV(50, '-');
  3. cout << "this vector has 50 char - :\n";
  4. for(k = 0; k < cV.size(); k++)
  5. {
  6. cout << cV[k];
  7. }
  8. cout << endl;
Last edited by Nick Evan; Feb 3rd, 2010 at 10:40 am.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Mar 11th, 2005
0

Re: C and C++ Timesaving Tips

How to remove duplicate elements from a vector ...

C++ Syntax (Toggle Plain Text)
  1. // load a vector with an integer array and remove duplicates
  2. ...
  3. int b[] = {0, 1, 2, 3, 4, 3, 4, 5, 6, 4};
  4. // load using (array, array + NumberOfElements)
  5. vector<int> iV4(b, b + sizeof(b)/sizeof(int));
  6.  
  7. // remove the duplicates with sort(), erase() and unique()
  8. cout << "removed the duplicate elements:\n";
  9. sort( iV4.begin(), iV4.end() );
  10. iV4.erase( unique( iV4.begin(), iV4.end() ), iV4.end() );
  11. // show the result
  12. for(k = 0; k < iV4.size(); k++)
  13. {
  14. cout << setw(8) << iV4[k];
  15. }
  16. cout << endl;
  17. ...
Last edited by Nick Evan; Feb 3rd, 2010 at 10:41 am.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Mar 13th, 2005
0

Re: C and C++ Timesaving Tips

Removing a newline in C

The fgets function in C is annoying in that it copies a newline character to the buffer:
C++ Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2.  
  3. int main ( void )
  4. {
  5. char buffer[BUFSIZ];
  6.  
  7. printf ( "Enter a string: " );
  8. if ( fgets ( buffer, sizeof buffer, stdin ) != NULL )
  9. printf ( "|%s|\n", buffer );
  10.  
  11. return 0;
  12. }
When you run this program and type "test", this is the output:
C++ Syntax (Toggle Plain Text)
  1. |test
  2. |
This is a good feature for dealing with long lines and such, but for the most part it serves only to frustrate beginners. Experienced programmers have learned to remove the newline with tricks such as:
C++ Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main ( void )
  5. {
  6. char buffer[BUFSIZ];
  7.  
  8. printf ( "Enter a string: " );
  9. if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
  10. size_t len = strlen ( buffer );
  11.  
  12. if ( buffer[len - 1] == '\n' )
  13. buffer[len - 1] = '\0';
  14.  
  15. printf ( "|%s|\n", buffer );
  16. }
  17.  
  18. return 0;
  19. }
Or more commonly:
C++ Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main ( void )
  5. {
  6. char buffer[BUFSIZ];
  7.  
  8. printf ( "Enter a string: " );
  9. if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
  10. char *newline = strchr ( buffer, '\n' );
  11.  
  12. if ( newline != NULL )
  13. *newline = '\0';
  14.  
  15. printf ( "|%s|\n", buffer );
  16. }
  17.  
  18. return 0;
  19. }
The annoying part of this issue is that one often is required to declare a variable, test for a newline character explicitly, and replace it explicitly. A quick timesaver when writing code is the strcspn function:
C++ Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main ( void )
  5. {
  6. char buffer[BUFSIZ];
  7.  
  8. printf ( "Enter a string: " );
  9. if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
  10. buffer[strcspn ( buffer, "\n" )] = '\0';
  11. printf ( "|%s|\n", buffer );
  12. }
  13.  
  14. return 0;
  15. }
The downside to this timesaver is that it doesn't save time during execution. The strcspn trick will usually be slower than most other methods of removing a newline. However, because the performance hit of input far outweighs any difference in speed for removing the newline character.
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Mar 16th, 2005
0

Re: C and C++ Timesaving Tips

Quote originally posted by Narue ...
Removing a newline in C

The fgets function in C is annoying in that it copies a newline character to the buffer:
instead of performing that little dance every time, i'd just write a new function and get it over with.

C++ Syntax (Toggle Plain Text)
  1. char *fget(char *s, int size, FILE * stream)
  2. {
  3. char *ptr;
  4. int c;
  5.  
  6. for (ptr = s; size > 1; --size) {
  7. c = getc(stream);
  8. if (c == EOF || c == '\n')
  9. break;
  10. *ptr++ = c;
  11. }
  12.  
  13. if (ptr == s) {
  14. ptr = NULL;
  15. } else {
  16. *ptr = 0;
  17. }
  18.  
  19. return ptr;
  20. }
wbk
Reputation Points: 10
Solved Threads: 0
Newbie Poster
wbk is offline Offline
13 posts
since Mar 2005
Mar 16th, 2005
0

Re: C and C++ Timesaving Tips

>i'd just write a new function and get it over with
That's one way to go about it, but since fgets is already there and is presumably written with performance in mind, it's smarter to make use of it:
C++ Syntax (Toggle Plain Text)
  1. char *reads ( char *s, size_t limit, FILE *stream )
  2. {
  3. if ( fgets ( s, limit, stream ) == NULL ) {
  4. return NULL;
  5. } else {
  6. char *newline = strchr ( s, '\n' );
  7.  
  8. if ( newline != NULL )
  9. *newline = '\0';
  10.  
  11. return s;
  12. }
  13. }
It's also easier to verify correctness when you use the standard library instead of trying to rewrite it.
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Mar 16th, 2005
0

Re: C and C++ Timesaving Tips

Quote originally posted by Narue ...
>i'd just write a new function and get it over with
That's one way to go about it, but since fgets is already there and is presumably written with performance in mind,
Presumably. But, having implemented the C89 stdlib in it's entirety I can assure you that the last thing it's designers had in mind when devising the stdio library was performance. If you require fast I/O, you'd do well to look elsewhere.

Quote ...
it's smarter to make use of it:
...
It's also easier to verify correctness when you use the standard library instead of trying to rewrite it.
It's easier to verify correctness when your functions have a single exit point (hint)
speaking of weird code, my function should return s and not ptr.
wbk
Reputation Points: 10
Solved Threads: 0
Newbie Poster
wbk is offline Offline
13 posts
since Mar 2005
Mar 16th, 2005
0

Re: C and C++ Timesaving Tips

>It's easier to verify correctness when your functions have a single exit point (hint)
That's debatable. Often it's harder in my experience because you have to bend over backward with unnecessary constructs to ensure a single exit point. For trivial functions such as the ones we posted, it's hardly brain surgery to verify correctness. For non-trivial functions, it's difficult to maintain simplicty and still adhere to structured programming "good practice". I prefer to err on the side of simplicity and transparency.

>had in mind when devising the stdio library was performance.
Performance was a primary concern for the design of C and its libraries. As another programmer who's implemented the C89 library in its entirety, I'm not entirely sure what you're referring to. Let me know in PM so we don't end up going too far off topic.

>speaking of weird code, my function should return s and not ptr
Oh good, I thought maybe my mentioning correctness was too subtle of a hint.
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Mar 20th, 2005
0

Re: C and C++ Timesaving Tips

Seeing as this thread is about timesaving what about inheritance? Its a good time saver especially for the masses intent on game creation.

Say you make a class such as

C++ Syntax (Toggle Plain Text)
  1. class CBASE_ENTITY
  2. {
  3. // code here. this class would provide functions for 'things' that exist in the game
  4. };

if you wanted to specialise and create objects such as moving platforms / players / weapon models ect you can simply

C++ Syntax (Toggle Plain Text)
  1. class CBASE_PLAYER : pubic CBASE_ENTITY {
  2. // player specific code.
  3. };

Without re-coding the entire class. Quite a few people forget inheritance and end up making some really messy classes! Dont forget that pointers are interchangable between derived and base classes which is VERY VERY useful....

An example of this timesaving would be to create a model cass, inherit a weapon class off it, and inherit weapons off the weapon base class. Then also pointers can be moved around the weapons derived classes.... im sure you can work out where this is going! If you look at the Half-Life source they make extensive use of inheritance to make a class oreentated (spelling) source which works very well....
Reputation Points: 16
Solved Threads: 6
Posting Pro in Training
1o0oBhP is offline Offline
445 posts
since Dec 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
This thread is currently closed and is not accepting any new replies.
Previous Thread in C++ Forum Timeline: not sure why program crashes
Next Thread in C++ Forum Timeline: helpppppp me with this program





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC