The solution is straightforward. But my guess is that this is not what you want.
And, I think that the last value in the row is not the sum . . .
But let us first look at one potential solution:
#include <iostream>
#include <algorithm>
#include <array>
constexpr size_t NumberOfRows = 4u;
constexpr size_t NumberOfColumns = 7u;
using Columns = std::array<int, NumberOfColumns>;
using Array = std::array<Columns,NumberOfRows>;
int main() {
Array array{{ {0, 2, 1, 1, 3, -2, 2},
{1, 1, 1, 3, 3, 0, 4},
{2, 0, 1, 3, 1, 2, 6},
{1, 1, 1, 2, 2, 0, 4} }};
std::sort(std::begin(array), std::end(array), [](const Columns& c1, const Columns& c2) {return c1[6] < c2[6]; });
for (const Columns& c : array) {
for (const int i : c) std::cout << i << '\t';
std::cout << '\n';
}
}
If you want the array to be dynamic, then you may use a std::vector
instead. You can then resize the number of rows and then number of columns.
#include <iostream>
#include <algorithm>
#include <vector>
constexpr size_t NumberOfRows = 4u;
constexpr size_t NumberOfColumns = 7u;
using Columns = std::vector<int>;
using Array = std::vector<Columns>;
int main() {
Array array{ {0, 2, 1, 1, 3, -2, 2},
{1, 1, 1, 3, 3, 0, 4},
{2, 0, 1, 3, 1, 2, 6},
{1, 1, 1, 2, 2, 0, 4} };
std::sort(std::begin(array), std::end(array), [](const Columns& c1, const Columns& c2) {return c1[6] < c2[6]; });
for (const Columns& c : array) {
for (const int i : c) std::cout << i << '\t';
std::cout << '\n';
}
}
But I still think that this is the wrong design. Becuase the last value in a row is the sum of other values. It is dependent, can be calculated, and there is no need to store ist.
See the following better design:
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
struct Result {
std::vector<int> values{};
int sum() const { return std::accumulate(values.begin(), values.end(), 0); }
friend std::ostream& operator << (std::ostream& os, const Result& r) {
for (const int i : r.values) os << i << '\t';
return os << "--> " << r.sum();;
}
};
struct Series {
std::vector<Result> results{};
friend std::ostream& operator << (std::ostream& os, const Series& s) {
for (const Result r : s.results) os << r << '\n';
return os;
}
};
int main() {
Series series{{
{{0, 2, 1, 1, 3,-2}},
{{1, 1, 1, 3, 3, 0}},
{{2, 0, 1, 3, 1, 2}},
{{ 1, 1, 1, 2, 2, 0}}
}};
std::sort(series.results.begin(), series.results.end(), [](const Result& r1, const Result& r2) {return r1.sum() < r2.sum(); });
std::cout << series;
}
But you did not give enough information to give a good answer.