【问题标题】:initialize struct array element with different value using memset in c++在 C++ 中使用 memset 初始化具有不同值的结构数组元素
【发布时间】:2014-08-24 20:59:15
【问题描述】:

在 C++ 中,

struct info
{
    int lazy,sum;
}tree[4*mx];

初始化:

memset(tree,0,sizeof(tree))

意思是

tree[0].sum is 0 and tree[0].lazy is 0 ...and so on.

现在我想像这样初始化不同的值:

tree[0].sum is 0 and tree[0].lazy is -1 .... and so on.

在 For 循环中

for(int i=0;i<n;i++) // where n is array size
{
    tree[i].sum=0;
    tree[i].lazy=-1;
}

但在 memset 函数中,我无法用不同的值初始化结构数组。是否可以 ??

【问题讨论】:

  • 不,单次调用 memset 是不可能的。使用std::fill

标签: c++ struct initialization memset


【解决方案1】:

memset 你传递给定地址范围的每个字节初始化的值。

memset - 将 ptr 指向的内存块的前 num 字节设置为 指定的值(解释为无符号字符)。

因此,你无法实现你想要的。

这就是 构造函数 的用途:

struct info
{
    int lazy,sum;
    info() : lazy(-1), sum(0) {}
} tree[4*mx];

// no need to call memset

或者您可以创建结构的模式并将其设置为tree 的每个元素:

#include <algorithm>

struct info
{
    int lazy,sum;
} tree[4];

info pattern;
pattern.lazy = -1;
pattern.sum = 0;

std::fill_n(tree, sizeof(tree)/sizeof(*tree), pattern);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-24
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2021-07-19
    • 2011-01-01
    相关资源
    最近更新 更多