我想用相同的值填充MyStruct数组。如何以最快和最简单的方式完成?我正在运行相当低级的方法,例如memset
或memcpy
。
编辑:std::fill_n
确实符合并且正常工作。但它是C ++的方式。 如何在纯C中完成?
struct MyStruct
{
int a;
int b;
};
void foo()
{
MyStruct abc;
abc.a = 123;
abc.b = 321;
MyStruct arr[100];
// fill 100 MyStruct's with copy of abc
std::fill_n(arr, 100, abc); // working C++ way
// or maybe loop of memcpy? But is it efficient?
for (int i = 0; i < 100; i++)
memcpy(arr[i],abc,sizeof(MyStruct));
}
答案 0 :(得分:6)
注意正确键入类型的名称(区分大小写)并且在struct
定义后不要忘记分号,除此之外,您的程序应该编译没有问题:
#include <iostream>
#include <algorithm>
struct MyStruct
{
int a;
int b;
}; // <------------- HERE
int main() {
MyStruct abc;
abc.a = 123;
abc.b = 321;
MyStruct arr[100];
std::fill_n(arr, 100, abc);
std::cout << arr[99].b;
}
输出321
。
“如何以最快最简单的方式完成?”
最简单的方法可能是使用std::vector
及其相应的构造函数:
#include <vector>
void foo()
{
MyStruct abc;
abc.a = 123;
abc.b = 321;
std::vector<MyStruct> vec(100, abc);
...
}
答案 1 :(得分:1)
for(int i = 0; i < 100; i++)
{
arr[i] = abc;
}
最快,最干净。优化器很可能也很有效。
答案 2 :(得分:0)
以下内容适用于C
MyStruct arr[100] = {
{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321}};
答案 3 :(得分:0)
不是纯粹的C,但是GCC允许你很好地完成它:
MyStruct arr[100] = { [ 0 ... 99 ] = { .a = 123, .b = 321 } };
如果您需要纯C,我会follow Tri-Edge Al's answer。
答案 4 :(得分:0)
我对C99的猜测将低于代码:
#include <stdio.h>
typedef struct MyStruct
{
int a ;
int b ;
} MyStruct_t;
const MyStruct_t abc =
{
.a = 0,
.b = 321,
};
void main(void)
{
int i = 0 ;
MyStruct_t arr[100] = {0} ;
for(i=0 ;i <sizeof(arr)/sizeof(arr[0]);i++)
{
arr[i] = abc ;
}
}
在我看来,这是最清洁,最安全的解决方案。