Swapping Characters

Jan 13, 2012 at 3:36am
Hi all,

I know you can swap strings using the .swap() function, but is it possible to swap characters? Any advice would be greatly appreciated.
Jan 13, 2012 at 3:41am
it is possible to write own CharSwap() function which will swap chars :)
Jan 13, 2012 at 3:49am
So there is no "automatic"(for lack of a better word) way like the string .swap() function?
Jan 13, 2012 at 3:53am
Yes it is :D

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main()
{
	char a = 'a';
	char b = 'b';
	swap<char>(a, b);
	cout << a << endl << b << endl;
	cin.ignore();  // stop cmd here 
	return 0;
}
Jan 13, 2012 at 3:59am
You need to #include <algorithm> : http://www.cplusplus.com/reference/algorithm/
Also you do not have to specify <char>, the compiler can deduce that for you :)
Last edited on Jan 13, 2012 at 4:00am
Jan 13, 2012 at 4:12am
You need to #include <algorithm>
you don't have to #include <algorithm> if you're using visual studio :D
Also you do not have to specify <char>

specifying <char> makes programers intention more understandable :)

Jan 13, 2012 at 12:19pm
you don't have to #include <algorithm> if you're using visual studio :D

It's just happen to work because one of the headers you include already includes <algorithm>.

specifying <char> makes programers intention more understandable :)

I don't see how specifying <char> makes it more understandable. a and b are chars so of course we want to swap chars.
Jan 13, 2012 at 12:25pm
Sounds to me like he wanted to swap characters of a string, i.e.:
1
2
3
string s = "This is a string!";
swap(s[2],s[8]);
cout << s;

Output: Thas is i string!
Topic archived. No new replies allowed.