【问题标题】:Passing a 2d array of structs in C++在 C++ 中传递一个二维结构数组
【发布时间】:2015-03-23 19:37:34
【问题描述】:

我正在尝试在不使用向量的情况下对 2D 结构数组进行洗牌。到目前为止,我的代码在一维中工作,但我无法将其扩展到二维。这是我目前所拥有的:

#include <iostream>
#include <algorithm>
#include <time.h>

using namespace std;

struct bingo {
    int set1;
    int set2;
};

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void randomize(int arr[], int n) {
    srand(time(NULL));

    for(int i = n-1; i > 0; i--) {
        int j = rand() % (i + 1);
        swap(&arr[i], &arr[j]);
    }
}

int main() {
    const int n = 28;
    bingo arr[n] = { // array of structs
        {0,1}, {1,2}, {2,3}, {3,4}
    };

    randomize(arr, n); // My error happens here and it says "cannot convert
                       // "bingo* to int* for argument '1' to void randomize(int*, int)

    for(int i = 0; i < n; i++) {
        std::cout << arr[i].set1 << arr[i].set2 << endl;
    }

    return(0);
}

【问题讨论】:

  • 嗯,是的。 randomize() 采用 int * 而不是 bingo。首先,您需要更改该函数以获取bingo *
  • 这是 C 还是 C++?你说 C 但标记为 C++。请使其成为有效的 C 或删除对 C 的提及。
  • @Vality 来自std::cout 的include 语句和用法,这显然是c++。 OP 似乎对实际使用的语言有误解。
  • 你可以使用std:swap而不是自己写
  • 使用std::vectorstd::random_shuffle

标签: c++ struct multidimensional-array shuffle


【解决方案1】:

您的代码中有类型错误。现在,您的代码将在“1d”中工作,因为您的所有函数只接受“1d”ints。但是现在使用您的“2d”版本,您需要将许多类型更改为bingo。进行这些更改,

第 12 行:void swap(int *a, int *b) {void swap(bingo *a, bingo *b) {

第 13 行:int temp = *a;bingo temp = *a;

第 18 行:void randomize(int arr[], int n) {void randomize(bingo arr[], int n) {

你得到的错误实际上是关于错误的非常有用的信息,所以要注意那些!

【讨论】:

    猜你喜欢
    • 2014-05-28
    • 2016-06-07
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 2011-04-20
    • 2014-03-15
    相关资源
    最近更新 更多