int beadArray[MAX] = {4};
此行将第一个元素初始化为 4,其余元素初始化为 0,而不是全部为 4。
使用向量的东西将来会更容易处理和更好:
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';
非矢量解决方案:
如果没有向量,仍然可以使用 STL 算法:
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
打印数组的一种更聪明的方法是使用 ostream 迭代器:
std::copy (beadArray, beadArray + MAX, std::ostream_iterator<int> (std::cout, "\t"));
只是简单的 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