gpt4 book ai didi

c++ - 用相同的值填充数组,循环重置值

转载 作者:行者123 更新时间:2023-11-28 03:37:55 24 4
gpt4 key购买 nike

我正在从事一个编程项目 (mancala),但在编写数组时卡住了。我需要编写一个数组,用值 4 填充所有板箱,然后将两个箱重置为 0。到目前为止我只有

{

    int i;
int beadArray[MAX] = {4};

for (i = 0; i < MAX; i++)
{
beadArray[i] = -1;
}

for (i = 0; i < MAX; i++)
{
cout<<i<<"\t";

}

最佳答案

int beadArray[MAX] = {4};

这一行将第一个元素初始化为4,其余元素初始化为0,不是全部初始化为4。

使用 vector 的东西在未来会更容易处理和更好:

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';

非 vector 解决方案:

没有 vector ,仍然可以使用 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

关于c++ - 用相同的值填充数组,循环重置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10308932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com