Re: newbie question
From: Ivan Vecerina (please_use_web_form_at_ivan.vecerina.com)
Date: 07/11/04
- Next message: Ivan Vecerina: "Re: newbie question"
- Previous message: Miguel: "Re: Floating point arithmetic."
- In reply to: BrianJones: "newbie question"
- Next in thread: Ivan Vecerina: "Re: newbie question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 11 Jul 2004 21:11:50 +0200
"BrianJones" <brian@jones1611.fsnet.co.uk> wrote in message
news:ccri2l$2nt$1@newsg2.svr.pol.co.uk...
> Having programmed in java for many years, I decided to try C++ for
speed...
> Anyway, am writing this simple encryption program, and a method I have
takes
> an array of chars (i.e. bytes) and swaps the two halves around e.g:
>
> 0,1,2,3,4,5,6,7,8 -> 5,6,7,8,4,0,1,2,3
>
> But - it doesn't work properly and I can't see the problem?
[others have answered this already]
> Any suggestions?
First of all, if your focus is on performance, you should understand
the performance of standard library functions and avoid unnecessary
pessimizations. For example, calling strlen() multiple times in your
code will imply a performance penalty. Also, it might be best to
avoid memory allocations: the data can be swapped in-place.
A 'performance-oriented' version of the function may look like:
#include <algorithm>
#include <cstring>
using namespace std;
// modifies the contentes of 0-terminated 'buf' as described above
void swapHalves(char* buf)
{
size_t const len = strlen(buf);
swap_ranges( buf, buf+len/2, buf+(len+1)/2 );
}
But as a newbie, I would start by taking advantage of standard
C++ classes such as std::string :
#include <string>
using namespace std;
// modifies the contentes of 0-terminated 'buf' as described above
string swapHalves(const string& src)
{
size_t const len = src.size();
string ans;
ans.reserve(len); // optional, may avoid memory reallocations
ans.append( src.end()-len/2, src.end() ); // start with 2nd half
if( 0!=len%2 )
ans.push_back( src[len/2] ); // appends a single character
ans.append( src.begin(), src.begin()+len/2 ); // append 1st half
return ans;
}
hth,
Ivan
-- http://ivan.vecerina.com/contact/?subject=NG_POST <- e-mail contact form Brainbench MVP for C++ <> http://www.brainbench.com
- Next message: Ivan Vecerina: "Re: newbie question"
- Previous message: Miguel: "Re: Floating point arithmetic."
- In reply to: BrianJones: "newbie question"
- Next in thread: Ivan Vecerina: "Re: newbie question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|