randomUser
randomUser

Reputation: 693

How to initialize all elements of a two-dimensional array to a particular value?

Is there is any function similar to memset() to initialize all elements of a two-dimensional array to a certain value? memset can only be used to initialize the values to 0 and -1.

Upvotes: 6

Views: 1674

Answers (2)

S.S. Anne
S.S. Anne

Reputation: 15566

You can use std::fill:

for(auto &arr : two_dim)
    std::fill(std::begin(arr), std::end(arr), value);

This will work for many arrays and containers, like std::vector, std::array, and C arrays.

Also note that you can use memset to initialize all elements of an array to values other than -1 and 0. It's just that all the bytes in each element will have the same value, like 0x12121212.

Upvotes: 4

Shafiul Alam Shiam
Shafiul Alam Shiam

Reputation: 50

Here is fill() function to initialize 2D array with certain value

#include <iostream>
#include <algorithm>

int a[row][column], value;
std::fill(a[0], a[0] + row * column, value);

Upvotes: 0

Related Questions