473,796 Members | 2,669 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

In-place function

Hi There,

Can you please help me write an in-place function in C++ for reversing
a string.

What is an in-place function?

So what is a non-in-place function in that case to reverse a C++
string?

Urgent help needed.

Thanks,

Peter.

Apr 3 '06 #1
7 2427
pe************* @gmail.com wrote:
Can you please help me write an in-place function in C++ for reversing
a string.


#include <string>
#include <algorithm>

void strrev(std::str ing &s) {
std::reverse(s. begin(), s.end());
}

That kind of homework question is sooo 1980's.

Apr 3 '06 #2
pe************* @gmail.com wrote:
Can you please help me write an in-place function in C++ for reversing
a string.


std::string s = "Hello, world!" ;
std::reverse(s. begin(), s.end()) ;
Apr 3 '06 #3
pe************* @gmail.com wrote:
Hi There,

Can you please help me write an in-place function in C++ for reversing
a string.

What is an in-place function?

So what is a non-in-place function in that case to reverse a C++
string?


I think it's about reversing the string in-place. It means that you don't
create a new string with the same content in reversed order, but rather you
modify the original string by exchanging characters.

Apr 3 '06 #4
In article <11************ *********@z34g2 000cwc.googlegr oups.com>,
pe************* @gmail.com wrote:
Hi There,

Can you please help me write an in-place function in C++ for reversing
a string.


#include <iostream>
#include <string>
// add includes as you think necessary

using namespace std;

void reverse( string& s ) {
// your code here
}

int main() {
string s( "AB" );
reverse( s );
assert( s == "BA" );
cout << "Working\n" ;
}

Cut and paste the above into your compiler. Add code to the "your code
here" section until 'Working' shows up on your screen when you run it.
Then post back here with what you did.

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Apr 3 '06 #5
posted:
Hi There,

Can you please help me write an in-place function in C++ for reversing
a string.

What is an in-place function?

So what is a non-in-place function in that case to reverse a C++
string?

Urgent help needed.

Thanks,

Peter.

This problem is so trivial that I'd challenge myself as to just how
efficient I can make it.

(Yes I realise I'm doing your homework, but this could be a laugh...)

The following code is unchecked and most likely doesn't work, but what the
hey:

#include <cstddef>
#include <cstring>
#include <iostream>
using std::cout; using std::endl;

/* The actual function */
void ReverseString( char* p_beginning, char* p_end )
{
for (;;)
{
std::swap( *p_beginning, *p_end );

switch (p_end++ - p_beginning++)
{
case 1: case 2: return;
}
}
}

/* The function whose argument is an array */
template<std::s ize_t i>
void ReverseString( char (&p_start)[i] )
{
ReverseString( &p_start[0], &p_start[i - 1] );
}

/* The function which takes a pointer, and also an integral length */
void ReverseString( char* const p_str, std::size_t len )
{
ReverseString( &p_str[0], &p_str[--len] );
}

/* The function which take a pointer */
void ReverseString( char* const p_start )
{
ReverseString( p_start, std::strlen(p_s tart) );
}

int main()
{
char monkey[] = "monkey";
char cow[] = "cow";
char niagra[] = "niagra";
char stringent[] = "stringent" ;

ReverseString( monkey ); ReverseString(c ow); ReverseString(n iagra);

ReverseString( &monkey[0] ); ReverseString( &cow[0] );

cout << monkey << cow << niagra << stringent;
}
-Tomás
Apr 3 '06 #6

Tomás wrote:
posted:
Hi There,

Can you please help me write an in-place function in C++ for reversing
a string.


This problem is so trivial that I'd challenge myself as to just how
efficient I can make it.

(Yes I realise I'm doing your homework, but this could be a laugh...)


How about this one :D
Probably gets bonus points from the teacher (or an instant F :D ):

#include <iostream>
#include <string>

std::string strinv( std::string s )
{
for( unsigned i=0; i<s.size()/2; ++i )
s[s.size()-i-1]^=s[i]^=s[s.size()-i-1]^=s[i];
return s;
}

int main()
{
std::string hello( "Hello World!" );
std::cout << strinv( hello ) << std::endl;
}

Cheers,
Andre

Apr 3 '06 #7
in*****@gmail.c om wrote:
Tomás wrote:
posted:
Hi There,

Can you please help me write an in-place function in C++ for reversing
a string.

This problem is so trivial that I'd challenge myself as to just how
efficient I can make it.

(Yes I realise I'm doing your homework, but this could be a laugh...)


How about this one :D
Probably gets bonus points from the teacher (or an instant F :D ):

#include <iostream>
#include <string>

std::string strinv( std::string s )
{
for( unsigned i=0; i<s.size()/2; ++i )
s[s.size()-i-1]^=s[i]^=s[s.size()-i-1]^=s[i];
return s;
}

int main()
{
std::string hello( "Hello World!" );
std::cout << strinv( hello ) << std::endl;
}

Come on, we could come up with something more obfuscated than that if we
really try! :-)
Apr 3 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6771
by: Curious Expatriate | last post by:
Hi- I'm completely stumped. I'm trying to write some code that will parse a file and rewrite it with all URLs replaced by something else. For example: if the file looks like this: <b>click here</b><a href="http://www.cnn.com">click me</a> ... then the output should be this:
1
6341
by: JS Bangs | last post by:
I started using PHP's object-oriented stuff a little while ago, which has mostly been a joy. However, I've noticed that they don't seem to echo as I would like. Eg: $this->field = 255; $this->key = 'id'; echo "$this->key is $this->field"; // prints "id is Array" // Thus I am forced to do this $keyval = $this->field;
5
16155
by: lawrence | last post by:
I've waited 6 weeks for an answer to my other question and still no luck, so let me rephrase the question. I know I can do this: <form method="post" action="$self"> <input type="text" name="filesToDelete"> <input type="text" name="filesToDelete"> <input type="text" name="filesToDelete"> </form>
1
8706
by: James | last post by:
What is the best way to update a record in a MYSQL DB using a FORM and PHP ? Where ID = $ID ! Any examples or URLS ? Thanks
1
3426
by: phpkid | last post by:
Howdy I've been given conflicting answers about search engines picking up urls like: http://mysite.com/index.php?var1=1&var2=2&var3=3 Do search engines pick up these urls? I've been considering converting a site of mine to PHP-Nuke, but if the individual modules aren't picked up in search engines I'm not going to do it. Thanks phpKid
1
2559
by: lawrence | last post by:
What is the PHP equivalent of messaging, as in Java?
10
3849
by: lawrence | last post by:
I get the impression that most people who are using objects in their PHP projects are mixing them with procedural code. The design, I think, is one where the procedural code is the client code, and the classes are a library of utility code. As such, when I've asked about how to get globals into objects, I've been told that I should pass them in as the parameters to a method. Easy enough if you have some procedural code. This answer I've...
2
27649
by: Phillip Wu | last post by:
Hi, I saw a previous post about sending arrays but did not quite understand the answers. The problem is that I would like to pass an entire array as a hidden input field from one php script to another. I've simplified the code where form1.php calls form2.php when "Go" is hit: form1.php
4
18671
by: Matt Schroeder | last post by:
Does anyone know how to count how many rows are in a mysql table? This is what I have, but it doesn't work right: <? $db = mysql_connect("localhost", "username", "password"); mysql_select_db("database",$db); $sql = "SELECT COUNT(*) FROM table"; $result = mysql_query($sql); echo "$result"; ?>
5
3338
by: Martin Lucas-Smith | last post by:
Is there any need to keep the final break in a switch which uses a default at the end? I.e: switch ($data) { case 'foo': # Action break;
0
9684
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10459
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10236
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9055
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6793
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5445
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.