im new in swapping

can someone help me? how can i swap array's element how can i swap array[]=( 2,3,1,4). how can i swap it to make this array (1,2,3,4)
/sarcasm on
1
2
3
#include <algorithm>
/*...*/
std::sort(array, array + 4);
/sarcasm off

If you want to swap two values, you can use std::swap function, or make swap manually like:
1
2
3
4
5
6
7
8
//we need to swap values of x and y
int x = 5, y = 10;

int temp = x; //
x = y;        //swapping
y = temp;     //

std::cout << x << ' ' << y;

For array elements:
1
2
3
4
//we want to swap elements 1 and 0
int temp = array[1];
array[1] = array[0];
array[0] = temp;

Or use std::swap: std::swap(array[1], array[0])
Last edited on
Look at:
http://www.cplusplus.com/reference/algorithm/swap/
It has both explanation about how it does swapping and an example on how to use it.

You could look at
http://www.cplusplus.com/reference/algorithm/sort/
for in your example case it would do the necessary swaps.
It looks like that you are required to write a sort function in which you will swap neighbour elements if the first one is greater than the second one.

EDIT: or you are required to use std::next_permutation.

For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <algorihm>
#include <iterator>

int main()
{
	int a[] = { 2, 3, 1, 4 };

	for ( int x : a ) std::cout << x << ' ';
	std::cout << std::endl;

	while ( std::next_permutation( std::begin( a ), std::end( a ) ) );

	for ( int x : a ) std::cout << x << ' ';
	std::cout << std::endl;
}


Last edited on
Topic archived. No new replies allowed.