Swapping Characters

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.
it is possible to write own CharSwap() function which will swap chars :)
So there is no "automatic"(for lack of a better word) way like the string .swap() function?
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;
}
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
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 :)

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.
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.