Google Answers Logo
View Question
 
Q: C++ swap ( Answered,   0 Comments )
Question  
Subject: C++ swap
Category: Computers > Algorithms
Asked by: jimmyjrosu-ga
List Price: $5.00
Posted: 01 Sep 2003 07:18 PDT
Expires: 01 Oct 2003 07:18 PDT
Question ID: 251027
I want to create a swap function that will work no matter what "type"
the incoming values are.  The two "types" to be swapped would be the
same: namely if I wanted to swap two stacks, say "x" and "y" where
"x"=<2, 3, 4> and 'y'=<5, 6, 7>, the values will be swapped.  I know
the normal swap function :type temp;
          temp=y;
          y=x;
          x=temp;
that function will only work with built in types, I need a function
that doesnt depend on the type.  Any ideas?

Clarification of Question by jimmyjrosu-ga on 01 Sep 2003 07:58 PDT
I would also accept as an answer a way to define '=' for a type other
than the built ins.  Namely, if I implement stack, how would I inlude
the ability to use '=' in the stack.  "stack a=stack b"

Request for Question Clarification by mathtalk-ga on 01 Sep 2003 08:49 PDT
For the list price offered, would you be interested in a link or two
discussing the use of template functions in C++ to accomplish this
sort of thing?

C++ is a strongly typed language, which means that any specific
function only works with arguments of a particular "type", although
two functions can have the same name (and thus differ only in the
types of calling arguments).  To avoid "rewriting" such functions for
each and every data type needed, one uses the device of a "template"
function, which allows the type of argument to be a parameter.

regards, mathtalk-ga

Clarification of Question by jimmyjrosu-ga on 01 Sep 2003 09:03 PDT
I dont think my question was clear.  I will detail the issue, I am
writing an implementation for "partialmap" , one function is "define"-
namely, that fuction has two parameters a (d, r) of type "type".  if
the "type" happened to be int or bool, i could just use say, d=j; but
if say type happened to be "stack".  So I would have a partialmap of
stacks (stack d, stack r)  if i tried to define a new stack to the
partial map, I couldnt use d=j;  so basically I need know if there was
a way to swap d and j, or define the "=" operator for stack. (and
partial map).  I know there are off the shelf components that are
similar to stack or partial map, I dont like the way they work.  Any
ideas?  I know swapping can be accomplished for an unknown type (of
course the type would be known after instantiation) I just dont know
how to do it.
Answer  
Subject: Re: C++ swap
Answered By: efn-ga on 01 Sep 2003 14:59 PDT
 
Hi jimmyjrosu,

There are two parts to the answer:  creating a template function and
creating an assignment operator.

As mathtalk suggested and you may already know, a template function
can work with various types.  In your case, it might look like this:

template <class T> void swap(T& x, T& y)
{
  T temp;
  // code as in your question
}

The use of templates is a big topic, about which whole books have been
written, and I suspect from your reference to instantiation that you
already know about them, so I will not go into further explanation
here.

The other part of the answer is how to define an assignment operator
for a class.  An assignment operator has to be a class member
function, usually declared like this:

class Fred
{
public:
  Fred& operator =(const Fred& rhs);
};

In the function definition, you do whatever is appropriate to copy the
content of rhs to the current object (*this).  ("rhs" is a traditional
name for the argument, standing for "right-hand side.")  If a class
just contains plain old data, this is straightforward; if the class
contains pointers, it's trickier.

If you don't declare an assignment operator, the compiler will
generate one for you, but if the class contains pointers, the
compiler-generated operator may not do what you need.

C++ gurus recommend that an assignment operator return *this, because
that is how built-in assignment operators work.  This is what enables
code like the following to work:

Fred a, b, c;
a = b = c;

The "b = c" part returns a reference to b, which is the right-hand
side of the assignment to a.

Another common bit of advice is to check for assignment to self.  This
avoids a possible problem where the assignment operator first trashes
the assignment target's content to make room for the new content, then
can't get the content from the rhs object because it's the same
object.

For more on assignment operators, see:

http://leepoint.net/notes/cpp/oop-overloading/overloadassign.html

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang98/HTML/_pluslang_assignment.asp

Having said all that, I should note that you don't need to write the
swap function because it is already in the standard library.  If you
use that function, you may need to define a copy constructor as well
as an assignment operator for your stack class.  (My reference on the
standard library says you do need a copy constructor, but the
implementation of the swap template in the compilers I have doesn't
use the copy constructor.)  But in general, any time you need an
assignment operator, it is a good idea to define a copy constructor
too.

The swap template function is in the <algorithm> header file.  For a
description, see:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcstdlib/html/vclrfalgorithmswap.asp


Search Strategy

The basic answer came from my knowledge of C++.  I found the web pages
referenced via searches for

C++ assignment operator

C++ algorithm library reference

I also referred to a couple of books:

C++ FAQs by Marshall Cline, Greg Lomow, and Mike Girou. 
Addison-Wesley (2nd ed., 1999)

The Standard C++ Library:  A Tutorial and Reference by Nicolai M.
Josuttis.  Addison-Wesley (November 1999).


I hope this information is helpful.  If you need more details about
any of this, please ask for a clarification.

--efn
Comments  
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy