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

C++多维数组仅打乱行的实现问题求助

Fixing Row-Only Shuffling for Your Custom Multidimensional Array

Hey there! I see you're trying to shuffle just the rows of your custom Array class, but the current std::shuffle call isn't working as expected. Let's break down why that's happening and how to fix it.

The Root Problem

Your current code uses shuffle(begin(dataSet), end(dataSet), g)—but if your custom Array class's begin() and end() iterators iterate over individual float elements (a flattened view of the array), then std::shuffle will mix up every single value instead of swapping entire rows. That's definitely not what you want!

The Solution: Shuffle Row Indices Instead

Instead of trying to shuffle the array directly, we'll create a list of row indices, shuffle those, then rebuild the array using the shuffled indices to rearrange rows. Here's how to adjust your shufflePoints function:

#include <vector>
#include <numeric> // For std::iota
#include <algorithm>
#include <random>

// Assuming your Array class has:
// - rows(): returns the number of rows
// - cols(): returns the number of columns
// - operator[] to access a row by index (and rows are copy-assignable)
Array<float,2,2> shufflePoints(Array<float,2,2> dataSet){
    random_device rd;
    mt19937 g(rd());
    
    // Create a vector of row indices (0, 1, 2, ..., number of rows - 1)
    vector<int> rowIndices(dataSet.rows());
    iota(rowIndices.begin(), rowIndices.end(), 0);
    
    // Shuffle the indices
    shuffle(rowIndices.begin(), rowIndices.end(), g);
    
    // Create a new array to hold the shuffled rows
    Array<float,2,2> shuffledDataSet = allocate(dataSet.rows(), dataSet.cols());
    
    // Assign rows in the shuffled index order
    for (size_t i = 0; i < rowIndices.size(); ++i) {
        shuffledDataSet[i] = dataSet[rowIndices[i]];
    }
    
    return shuffledDataSet;
}

Key Notes

  • Make sure your Array class supports:
    1. A rows() method to get the total number of rows.
    2. A cols() method to get the number of columns per row.
    3. Row access via operator[] (where dataSet[i] returns a reference to the i-th row, which can be copied to another row).
  • If your Array doesn't have rows()/cols(), you can hardcode the row count (4 in your example) temporarily, but adding those methods will make the code reusable.

Quick Check for Your Existing Code

Also, I noticed you're using Array<float,2,2> but allocating a 4x4 array—double-check that your template parameters align with the actual dimensions your allocate function creates. This might not be the root of the shuffling issue, but it's good to confirm for consistency.

内容的提问来源于stack exchange,提问作者Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:26:25