-3

将 2-dim 数组设置为 double 的最快方法是什么,例如 double x[N][N] all to -1?

我尝试使用 memset,但失败了。有什么好主意吗?

4

7 回答 7

2

使用:std::fill_n来自algorithm

std::fill_n(*array, sizeof(array) / sizeof (**array), -1 );

例子:

double array[10][10];
std::fill_n( *array, sizeof(array) / sizeof (**array), -1.0 );

//Display Matrix
for(auto i=0;i<10;i++)
{
    for(auto j=0;j<10;j++)
        cout<<array[i][j]<< " ";    
    cout<<endl;
}
于 2013-07-29T12:00:25.470 回答
1

也可以直接设置

    double x[4][4] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1} 

如果数组索引很小。

于 2013-07-29T12:00:27.843 回答
1
// create constants
const int rows = 10;
const int columns = 10;

// declare a 2D array
double myArray [rows][columns];

// run a double loop to fill up the array
for (int i = 0; i < rows; i++) 
    for (int k = 0; k < columns; k++)
        myArray[rows][columns] = -1.0;

// print out the results
for (int i = 0; i < rows; i++) {
    for (int k = 0; k < columns; k++)
        cout << myArray[rows][columns];

    cout << endl;
}
于 2013-07-29T12:41:57.537 回答
1

一个简单的循环:

#include <stdio.h>

int main(void)
{
    #define N 5
    double x[N][N];
    size_t i, n = sizeof(x) / sizeof(double);

    for (i = 0; i < n; i++)
        x[0][i] = -1.0;
    for (i = 0; i < n; i++)
        printf("%zu) %f\n", i, x[0][i]);
}
于 2013-07-29T12:06:33.263 回答
0

使用 C++ 容器,您可以使用填充方法

array<array<double, 1024>, 1024> matrix;

matrix.fill(-1.0);

如果由于某种原因,您必须坚持使用 C 样式的数组,您可以手动初始化第一行,然后将 memcpy 初始化到其他行。无论您是否将其定义为静态数组或逐行分配,这都有效。

const int rows = 1024;
const int cols = 1024;
double matrix[rows][cols]

for ( int i=0; i<cols; ++i)
{ 
    matrix[0][cols] = -1.0;
}
for ( int r=1; r<rows; ++r)
{
    // use the previous row as source to have it cache friendly for large matrices
    memcpy(&(void*)(matrix[row][0]), &(void*)(matrix[row-1][0]), cols*sizeof(double));
}

但我宁愿尝试从 C 样式数组转移到 C++ 容器,也不愿做那种特技。

于 2013-07-29T12:28:11.157 回答
0

memset不应该在这里使用,因为它基于void *. 所以所有的字节都是一样的。(float) -10xbf800000double0xbff0000000000000)所以并非所有字节都相同......

我会使用手动填充:

const int m = 1024;
const int n = 1024;
double arr[m][n];
for (size_t i = 0; i < m*n; i++)
    arr[i] = -1;

矩阵就像内存中的数组,所以最好有 1 个循环,它会稍微快一些。

或者你可以使用这个: std::fill_n(arr, m*n, -1);

不确定哪个更快,但两者看起来相似。所以可能你需要做一些小测试才能找到它,但据我所知,人们通常使用一个或另一个。另一件事,第一件事更多的是C在某些编译器上不起作用,第二件事是真实的C++,永远不会起作用C。所以你应该选择我认为的编程语言:)

于 2013-07-29T12:36:57.517 回答
0

使用std::array及其fill方法:

#include <array>
#include <iostream>

int main()
{
  const std::size_t N=4
  std::array<double, N*N> arr; // better to keep the memory 1D and access 2D!
  arr.fill(-1.);
  for(auto element : arr)
    std::cout << element << '\n';
}
于 2013-07-29T12:06:45.407 回答