Reputation: 33
Instead of setting up a loop to go through each position of this array and set it equal to this dot
int arraySize=50;
char board[arraySize];
for(i=0; i<arraySize; i++)
board[i]='.';
Is there any way I can declare an array to be filled with these '.' right away?
e.g. char board[arraySize]={'.'};
Upvotes: 3
Views: 12167
Reputation: 23324
Use std::array instead, then you can use fill.
#include <array>
[..]
std::array<char, 50> board;
board.fill('.');
But be aware, this is C++11 and internally there is a loop over your array, too. You get less and cleaner code, but it isn't faster.
Upvotes: 1
Reputation: 29724
std::vector
is a C++ way to deal with array which size can be changed at run time:
std::vector<char> v( 50, '.'); // a vector with 50 dots
http://en.cppreference.com/w/cpp/container/vector
Upvotes: 0
Reputation: 6853
The issue with that declaration is that you allocate memory at compile time using a size that is known only at run time. arraySize may change at anytime. If you say for example:
#define ARRAY_SIZE 50
char board[ARRAY_SIZE];
This way the size to be allocate is known at compile time and the compiler wont complain.
Then you can initialize using: memset(array, '.', size_of_array);
Another option you allocate at runtime using new
and use "value initialization" like this:
char * board = new char[arraySize]();
This will allocate AND initialize the array for you at runtime.
Upvotes: 1
Reputation: 42964
An option you have is to use std::vector
, and specify the initial "fill" value in the proper constructor overload:
#include <vector> // For std::vector
....
std::vector<char> board(arraySize, '.');
If you really need a raw C array, you can always use std::fill()
to simply fill it with some value:
#include <algorithm> // For std::fill
#include <iterator> // For non-member std::begin and std::end
....
static const int arraySize = 50;
char board[arraySize];
fill(begin(board), end(board), '.');
Another option is to use std::array
(which is lightweight and zero-overhead like a raw C array, but offers a C++ STL interface too):
#include <algorithm> // For std::fill
#include <array> // For std::array
....
static const int arraySize = 50;
std::array<char, arraySize> board;
std::fill(board.begin(), board.end(), '.');
// or just:
// board.fill('.');
// Since std::array has a fill() method.
(Frankly, in C++, I think that if you really need to use a statically-sized fixed-size array, std::array
is better than raw C arrays.)
Upvotes: 0
Reputation: 16106
Instead of an array, you could construct a vector in this way:
vector<char> board(arraySize, '.');
Vectors can then be used like an array:
char c = board[1];
Upvotes: 4
Reputation: 97
As far as i know, the only way to achieve that would be to actually do what you posted char board[arraySize]={'.', '.','.'......(50 times)}, but actually copy and paste that '.' 50 times, which is a hassle and not smart. So the for loop works, or using vectors!
Upvotes: 1