Sign in to follow this  

Swap Function

Recommended Posts

I was working on a program that took a list of words and placed them in alphabetical order. It involved using a swap funciton of my own design. Except, when I tried using it, I realized that the swap didn't work at all. I remember reading something about this in one of my beginner books but I can't find where. If you want to look at my code here it is. void Swap( string one, string two) { _ string temp; _ temp = one; _ one = two; _ two = temp; } Any help will be appreciated. Note: I realized later that the String class comes with its own swap function but I'm still wondering why this one didn't work

Share this post

Link to post
Share on other sites
0) You should state what language you're using if it isn't already clear from context. I'm assuming C++ here.

1) It's not std::string which has a swap function; instead, there is a *global* swap function that can swap any two things, as long as they're the same type, and can be assigned to each other.

2) The concept you are looking for is called "pass by reference". In C++, we do it by accepting reference types in our function:

void Swap(std::string& one, std::string& two) {

Notice the &s. This way, the strings that the function uses are the caller's strings, so the assignments change the caller's variables. When we "pass by value" (i.e. accept strings instead of references-to-string), the function gets copies of the caller's data. The copies get swapped around, and then (because they are local to the function) thrown away.

3) You could always try looking up how your compiler implements it. :) In normal implementations, those standard library headers (like "string" and "algorithm") are actual files on disk, somewhere in your compiler's install directory. (But they don't have to be; that's part of why there aren't any ".h" extensions on the C++ standard library headers - it wouldn't make any sense to have a file extension for a non-file!) Some things in the standard library - especially containers - are pretty ugly, but the "algorithms" - things like std::swap - are usually straightforward. You might have to chase headers though (i.e. the thing you're looking for is actually #included from somewhere else, perhaps indirectly...).

4) If you want to place words in alphabetical order, don't write your own swap function and use it to sort; don't even use the standard library swap to sort. Instead, use the standard library sorting function. :)

std::vector<std::string> words;
// put words into the vector here
std::sort(words.begin(), words.end());

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this