문제

In c++, we usually use memset to set all elements to zero like:

int a[5][5];
memset(a,0,sizeof(a));

What if I want set all int elements to 1?

memset(a, 1, sizeof(a));

doesn't work since I cannot just set all bytes to 1.

I wonder if there is similar function as memset to set all elements(NOT JUST BYTES) to a particular value.

도움이 되었습니까?

해결책

Using std::fill will work, but you have to resort to using reinterpret_cast<>, which is often considered bad form:

#include <algorithm>

int a[5][5];
std::fill(reinterpret_cast<int*>(a),
          reinterpret_cast<int*>(a)+(5*5),
          1);

Alternatively, you could take the address of the first element, which is likewise clunky:

std::fill(&a[0][0],&a[0][0]+(5*5),1);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top