sort 2d array

how would you sort int arr[3][3]= { { 2, 7, 6 }, { 9, 5, 1 }, {4,3,8} }; ?
Last edited on
How should sorted array looks?
1,2,3,4,5,6,7,8,9
So it is simple: std::sort(&arr[0][0], &arr[0][0] + 9);

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

int main()
{
	int arr[3][3]= { { 2, 7, 6 }, { 9, 5, 1 }, {4,3,8} };
	std::sort(&arr[0][0], &arr[0][0] + 9);

	for(auto& i: arr)
		for (auto j: i)
			std::cout << j << ' ';
}
1 2 3 4 5 6 7 8 9

@MiiNiPaa, how do you set code and output side by side ?
@MiiNiPaa, how do you set code and output side by side ?
http://www.cplusplus.com/articles/z13hAqkS/
@MiiNiPaa
1
2
for(auto& i: arr)
		for (auto j: i)

what does auto means in for loop?
i just know about the auto storage class and the one that assumes the data type in c++11
This is range-based-for loop.
http://en.cppreference.com/w/cpp/language/range-for
http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html

Auto here means same thing like it does in variable declaration: let compiler deduct type of variable itself.

Without it you would need to write (reference to array of 3 ints) type yourself, which is not trivial for most. We need to make it reference, becuse you cannot pass arrays by value.

Variant without auto:
1
2
3
for(int(&i)[3]: arr)
	for (int j: i)
		std::cout << j << ' ';
std::sort(&arr[0][0], &arr[0][0] + 9);

std::sort(&arr[0][0], &arr[2][2]);

both requires #include <algorithm>
Last edited on
std::sort(&arr[0][0], &arr[2][2]);
Not the same thing. Try it out.
If you want to get rid of magic numbers: std::sort(&arr[0][0], &arr[0][0] + sizeof(arr)/sizeof(int));
Last edited on
Not the same thing.
is there any difference?
Yes.
1
2
&arr[0][0], &arr[0][0] + 9
std::sort(&arr[0][0], &arr[2][2]);
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 9 8
thanks.
closed account (D80DSL3A)
Isn't the difference a matter of giving "one past the end" vs not?
1
2
&arr[0][0], &arr[2][2]// last element
&arr[0][0], &arr[2][3]// one past the end
123456798
123456789
Last edited on
arr[2][3] is illegal. You cannot actually access one-past-the-end element legally.
Best you can do is: (arr[2] + 3).
Topic archived. No new replies allowed.