简体   繁体   English

如何使用 memset 填充数组的最大值?

[英]How to use memset to fill in max value for an array?

Here is my code, I would need to fill in every element in the 2d array with the maximum size ( INT_MAX), however, my code was unable to work properly?这是我的代码,我需要用最大大小(INT_MAX)填充二维数组中的每个元素,但是,我的代码无法正常工作?

#include <iostream>
#include <string.h>
#include <limits.h>
using namespace std;
int main(){
    int arr[10][10];
    memset(arr,INT_MAX, sizeof (arr));
    cout << arr[0][3];
//output = -1 instead of 2147483647


}

How do I modify my code such that I will be able to fill in an array with the max values?如何修改我的代码,以便能够用最大值填充数组?

C++ Standard Library has a function fill_n to fill arrays with n values. C++ 标准库有一个 function fill_nn值填充 arrays。

#include <algorithm>
...
std::fill_n(&arr[0][0], 100, INT_MAX);

The number of values may be brittle here - if you change the size of the array in future, you have to remember to change the hard-coded 100 to a new correct value.这里值的数量可能很脆弱 - 如果您将来更改数组的大小,您必须记住将硬编码的100更改为新的正确值。

It's good enough for a quick hack.对于快速破解来说已经足够了。 If you need something with long-term value, use the idea in this answer to a similar question.如果您需要具有长期价值的东西,请使用此答案中的想法来回答类似问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM