You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按特定顺序将std::vector数据写入N×N矩阵右上三角区

Solution: Writing Vector Data to Upper Right Triangle in Specific Order

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:

  1. Calculate the difference d for the group containing the data index. Find the largest integer d where the sum of elements in groups with d' > d is less than your data index.
    • Sum of elements before group d is: sum = ( (N - d - 1) * (N - d) ) / 2
  2. The row within the group is data_index - sum
  3. Column is row + d

For example, data[5] in a 5×5 matrix:

  • We find d=2 because sum for d>2 is 1+2=3 ≤5, sum for d>1 is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:32:59