Swap function.
Feb 20, 2012 at 8:57am UTC
Can someone explain to me, or even show me how to write a complete function that swaps the values of two specified array elements.Thank you.
Feb 20, 2012 at 9:17am UTC
the header "algorithm" has a function std::swap(a, b) wich swaps the values of a and b.
example:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int array[]={1, 2};
cout<<array[0]<<" " <<array[1]<<endl;
swap(array[0], array[1]);
cout<<array[0]<<" " <<array[1];
return 0;
}
output:
Last edited on Feb 20, 2012 at 9:18am UTC
Feb 20, 2012 at 10:45am UTC
You do it the same way you would to swap 2 values (for example, an int "array element" is considered the same as an int a;)
Feb 20, 2012 at 12:34pm UTC
viliml ,
While using std::swap is the way that you should swap elements in an array it dose not explain
'how to write a complete function that swaps the values' that the OP requested.
Theharpman ,
A naive
* implementation of swap:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <iostream>
// a naive implementation of swap
void swap(int & a, int & b)
{
int temp = a;
a = b;
b = temp;
}
// A template version of the above
template <typename T>
void swap(T &a, T &b)
{
T t = a;
a = b;
b = t;
}
int main(void )
{
int an_array[] = {1, 2};
std::cout << an_array[0] << " " << an_array[1] << std::endl;
swap(an_array[0], an_array[1]);
std::cout << an_array[0] << " " << an_array[1] << std::endl;
// template version
double a_double_array[] = {1.1, 2.2};
std::cout << a_double_array[0] << " " << a_double_array[1] << std::endl;
swap(a_double_array[0], a_double_array[1]);
std::cout << a_double_array[0] << " " << a_double_array[1] << std::endl;
return 0;
}
* By naive I just mean simple, straight forward version.
Topic archived. No new replies allowed.