C++ memset() 用于长(64 位)类型
可能的重复:
是否有 memset() 接受大于 char 的整数?
从memset的声明中可以看出:
void * memset ( void * ptr, int value, size_t num );
有没有办法使用这个memset函数(或STL库中包含的另一个函数),以便您可以将内存设置为long long类型 价值?
我用它来初始化一个具有大值的 long long 数组。
我不得不说,我已经通过简单地迭代数组的每个值并将其设置为所需的值来“解决”了这个问题。
Possible Duplicate:
Is there memset() that accepts integers larger than char?
As it can be seen in memset's declaration:
void * memset ( void * ptr, int value, size_t num );
Is there any way to use this memset function (or another function included in STL library) so that you can set memory to a long long type value?
I use this to initialize an array of long longs with a large value.
I have to say that I've "solved" this problem by simply iterating through each value of the array and setting it to the desired value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
memset
仅使用传入值的一个字节并进行字节初始化。如果您想使用特定值初始化long long
数组,只需使用std::fill
或std::fill_n
并让您的库编译器会尽可能地优化它(部分循环展开等)。另一种规范的 C++ 方法是仅使用
vector
并让其构造函数为您完成工作:std::vectorfoo(数组长度,12345678901234LL);
memset
only uses one byte of the value passed in and does bytewise initialization. If you want to initialize along long
array with a particular value, just usestd::fill
orstd::fill_n
and let your library and compiler optimize it as they can (partial loop unrolling etc).Another canonical C++ way is to just use
vector
and let its constructor do the work for you:std::vector<long long> foo(length_of_array, 12345678901234LL);
使用 memcpy 对我来说似乎很慢,您的编译器支持本机 64 位整数,在这种情况下,如果您在发布模式下编译,则直接使用 int64 应该会更有效。
然而,考虑到现在编写的这个函数仅支持计数为 8 的倍数。
如果您需要处理任何类型的字节数,则需要处理小端大端问题。
但我们使用的是 C++,对吗?
让我们使用更面向 C++ 的东西。
正如评论中所述,还有函数
std:fill
Using memcpy seems slow to me, you have support for native 64 bit integers in your compiler, in this case this function should be more efficient using directly int64 if you are compiling in release mode.
However, consider that this function as it is written now supports only count as to be a multiple of 8.
If you need to work with any kind of number of bytes you need to deal with the little-endian big-endian problem.
But we are on C++ right?
Let's use something more C++ oriented.
As noted in comments, there is also the function
std:fill
memset 仅使用“值”的最低 8 位 - 它意味着将单个值复制到每个内存位置。它不会尝试或尝试处理可能会引入字节顺序等问题的多字节值。
如果您想用 long long 值填充内存,我可能会好奇为什么要这样做 -可能有更好的方法。
memset only uses the lowest 8 bits of 'value' - it's meant to copy a single value to every memory location. It doesn't try or attempt to deal with multi-byte values that might introduce issues with endianness etc.
If you want to fill memory with a long long value, I'd probably be curious as to why you want to do that -- there is probably a better way.
您可以使用 memcpy 函数来执行此操作。假设你的 long long 类型是 8 个字节,你可以这样做:
You can use the
memcpy
function to do this. Assuming your long long type is 8 bytes, you can do something like: