user1242967
user1242967

Reputation: 1290

How to change all elements of an array to specific value?

For example I have an array like this:

bool log[100000]

And I have loop in which I want to set the value of all elements in log to True. In other words, I want to wipe all the changes what have been done to log after each cycle of the loop. How could I do it? Could I change not all but let's say 100 values?

Upvotes: 1

Views: 5072

Answers (1)

James McNellis
James McNellis

Reputation: 355009

To fill the entire array with true:

std::fill(begin(log), end(log), true);

To fill the first 100 elements with true:

std::fill(begin(log), begin(log) + 100, true);

begin and end are added in C++11; if your compiler and library don't support them, consider using std::array<bool, N> instead, which has begin and end member functions. You really should use the std::array template anyway, since it has no overhead, provides the standard sequence container interface, and helps you to avoid the silly semantics of C arrays.

Upvotes: 5

Related Questions