问题
I'm working on a programming project (mancala) and have gotten stuck when writing an array. I need to write an array that fills all board bins with the value of four, and then resets two bins to 0. So far I only have
{
int i;
int beadArray[MAX] = {4};
for (i = 0; i < MAX; i++)
{
beadArray[i] = -1;
}
for (i = 0; i < MAX; i++)
{
cout<<i<<"\t";
}
回答1:
int beadArray[MAX] = {4};
This line initializes the first element to 4, and the rest to 0, not all of them to 4.
Something using vectors would be easier to handle and better in the future:
std::vector<int> beadArray (MAX, 4); //MAX elements, initialized to 4
beadArray [indexToReset1] = 0; //reset one element
beadArray [indexToReset2] = 0; //reset other element
//print array - C++11
for (int bead : beadArray)
cout << bead << '\t';
//print array - C++03, consider using std::for_each instead
for (vector<int>::const_iterator it = beadArray.begin(); it != beadArray.end(); ++it)
cout << *it << '\t';
Non-vector solution:
Without vectors, STL agorithms could still be used:
int beadArray [MAX];
std::fill (beadArray, beadArray + MAX, 4);
beadArray [6] = beadArray [13] = 0; //just the two elements
std::fill (beadArray + 6, beadArray + 13, 0); //the range of elements from 6-13
A somewhat more clever way to print the array would be to use an ostream iterator:
std::copy (beadArray, beadArray + MAX, std::ostream_iterator<int> (std::cout, "\t"));
Just plain C++:
int beadArray [MAX];
for (int i = 0; i < MAX; ++i)
beadArray [i] = 4; //set every element to 4
beadArray [6] = beadArray [13] = 0; //set elements 6 and 13 to 0
for (int i = 0; i < MAX; ++i)
cout << beadArray [i] << '\t'; //print each element separated by tabs
回答2:
Why do you specify that you want to use a loop to fill in indices 6 and 13? If you're only filling in two values a loop is not necessary.
Since this is only for a mancala game, if you don't need to use numbers larger than 255 (the maximum value a single byte can hold) then you can use an unsigned char array and memset.
char beadArray[MAX];
memset( beadArray, 4, sizeof(beadArray));
beadArray[6] = beadArray[13] = 0;
for( int i = 0; i < sizeof(beadArray); i++)
cout << beadArray[i] << "\t";
来源:https://stackoverflow.com/questions/10308932/filling-an-array-with-the-same-value-looping-to-reset-values