reverse char array in one pass

D

Darshan

hello guys,

can anyone tell me how to reverse a char array in a single pass?

thank you.
 
V

Victor Bazarov

Darshan said:
can anyone tell me how to reverse a char array in a single pass?

You can use 'std::swap' to exchange the first and the last element of an
array, right? Then you can use 'std::swap' to exchange the second and
the penultimate elements, yes? Then you can take another step, and
exchange the third elements from the beginning and the end... And keep
doing it until the "from beginning" pointer is the same or greater than
the "from end" pointer. Then stop.

BTW, this is covered in the FAQ 5.2. Read the FAQ before posting.

V
 
J

Jerry Coffin

hello guys,

can anyone tell me how to reverse a char array in a single pass?

std::swap would probably be useful. Beyond that, the primary trick is
knowing the size of the array, so you know what to swap. If possible,
a vector<char> or just std::string will make that a lot easier.
 
A

arunix

hello guys,

can anyone tell me how to reverse a char array in a single pass?

thank you.

You can use STL Algorithm reverse for it.
reverse((char-Array(start)),(char-Array(end)));
 
T

terminator

hello guys,

can anyone tell me how to reverse a char array in a single pass?

thank you.

the only way is to have a pascal-like string structure(std::string
maybe)that calculates the length at construction.but If you need a
true single pass solution ,my suggestion is either to use the
preprocessor directive *#define* to hard-code the size of literal ,or
to get a template constructor for your string class:

template<int sz>
mystr::mystr(char[sz]& );/*

literal string size calculation at compile time
+
step by step size calculation at modification (concating ,....)

*/

and remmember :
Any data originates from some Meta.

So Do not lose that Meta if you need optimization.In this problem Meta
is the size as well as literal value.

reguards,
FM.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,188
Latest member
Crypto TaxSoftware

Latest Threads

Top