按特定顺序将std::vector数据写入N×N矩阵右上三角区
First, let's break down the pattern you described using the 5×5 example. Notice each matrix element is grouped by the difference d = column - row:
- For
d = 4(max possible difference in a 5×5 matrix), we have 1 element:(0,4)→ data[0] - For
d =3, we have 2 elements:(0,3),(1,4)→ data[1], data[2] - For
d=2, 3 elements:(0,2),(1,3),(2,4)→ data[3], data[4], data[5] - And so on, until
d=0(the main diagonal), which has 5 elements.
The order is simple: iterate d from the maximum value (N-1) down to 0. For each d, loop through all valid rows where column = row + d stays within the matrix bounds (i.e., row ≤ N-1 -d).
Step-by-Step Implementation
Here's a straightforward C++ implementation that writes your vector data into the matrix following this pattern:
#include <vector> #include <iostream> int main() { const int N = 5; // Adjust this to your matrix size std::vector<std::vector<int>> matrix(N, std::vector<int>(N, 0)); std::vector<int> data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; // Example data int data_index = 0; // Iterate d from largest to smallest (N-1 down to 0) for (int d = N - 1; d >= 0; --d) { // For each valid row where column = row + d is within matrix bounds for (int row = 0; row <= N - 1 - d; ++row) { int col = row + d; matrix[row][col] = data[data_index++]; } } // Print the matrix to verify for (const auto& r : matrix) { for (int val : r) { std::cout << val << "\t"; } std::cout << "\n"; } return 0; }
Reverse Mapping: Data Index to Matrix Indices
If you need to find which matrix position corresponds to a given data index, use this formula:
- Calculate the difference
dfor the group containing the data index. Find the largest integerdwhere the sum of elements in groups withd' > dis less than your data index.- Sum of elements before group
dis:sum = ( (N - d - 1) * (N - d) ) / 2
- Sum of elements before group
- The row within the group is
data_index - sum - Column is
row + d
For example, data[5] in a 5×5 matrix:
- We find
d=2because sum ford>2is 1+2=3 ≤5, sum ford>1is 1+2+3=6>5. - Row =5-3=2, Column=2+2=4 → which matches your example (
mtr[2][4]).
This approach works for any N×N matrix, as long as your data vector has exactly N*(N+1)/2 elements (the number of elements in the upper right triangle including the diagonal).
内容的提问来源于stack exchange,提问作者kekyc

