簡體   English   中英

僅在C ++中隨機播放多維數組的行

[英]Shuffle only rows of multidimensional array in C++

我是C ++的初學者,因此在改組多維數組的行時面臨問題。 我查看了相關的解決方案,但並沒有太大幫助。 到目前為止,這是我嘗試過的:

int main(int argc, char **argv){

    Array<float, 2, 2> f1;
    f1 = allocate(4, 4);
    f1[0][0] = 1.0;
    f1[0][1] = 2.0;
    f1[0][2] = 3.0;
    f1[0][3] = 4.0;

    f1[1][0] = 5.0;
    f1[1][1] = 6.0;
    f1[1][2] = 7.0;
    f1[1][3] = 8.0;

    f1[2][0] = 9.0;
    f1[2][1] = 10.0;
    f1[2][2] = 11.0;
    f1[2][3] = 12.0;

    f1[3][0] = 13.0;
    f1[3][1] = 14.0;
    f1[3][2] = 15.0;
    f1[3][3] = 16.0;

    Array<float,2,2> feature1shuffled = shufflePoints(f1);
    cout<<feature1shuffled<<endl;
    return 0;
}

Array<float,2,2> shufflePoints(Array<float,2,2> dataSet){

    random_device rd;
    mt19937 g(rd());

    shuffle(begin(dataSet), end(dataSet), g);

    return dataSet;
}

但是它不能基於行正確地隨機播放。 有人可以幫我嗎?

這是一個工作示例。 它使用std :: array:

#include <algorithm>
#include <random>
#include <array>
#include <iostream>
#include <iterator>

template <typename T, size_t x, size_t y>
using Array = std::array<std::array<T, x>, y>; // use std::array

using std::cout;
using std::endl;
using std::random_device;
using std::mt19937;
using std::begin;
using std::end;

// print array
std::ostream& operator<<(std::ostream& os, const Array<float, 4, 4>& ar)
{
    for(const auto& i : ar) {
        for(const auto& j : i) {
            std::cout << j << '\t';
        }
        std::cout << '\n';
    }
    return os;
}

Array<float, 4, 4> shufflePoints(Array<float, 4, 4> dataSet){

    random_device rd;
    mt19937 g(rd());

    // this will shuffle the rows but not the elements within them
    shuffle(begin(dataSet), end(dataSet), g);

    return dataSet;
}

int main(int argc, char **argv){

    Array<float, 4, 4> f1{}; // elements set to 0
    //f1 = allocate(4, 4); // not required
    f1[0][0] = 1.0;
    f1[0][1] = 2.0;
    f1[0][2] = 3.0;
    f1[0][3] = 4.0;

    f1[1][0] = 5.0;
    f1[1][1] = 6.0;
    f1[1][2] = 7.0;
    f1[1][3] = 8.0;

    f1[2][0] = 9.0;
    f1[2][1] = 10.0;
    f1[2][2] = 11.0;
    f1[2][3] = 12.0;

    f1[3][0] = 13.0;
    f1[3][1] = 14.0;
    f1[3][2] = 15.0;
    f1[3][3] = 16.0; // Array must have dimensions of 4, 4 to access subscripts [3][3]

    Array<float, 4, 4> feature1shuffled = shufflePoints(f1);
    cout << feature1shuffled << endl;
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM