[英]I can't figure out how to fill an array
I am trying to fill a given array with a passed in value so if I wanted an array to be all 12's it would simply replace all the elements with 12s. 我试图用传入的值填充给定的数组,所以如果我想让数组全部为12,则只需将所有元素替换为12s。 The prototype I have for this function looks like this:
我具有此功能的原型如下所示:
void fill(T *left, T *end, T fill)
The driver for this function looks like this: 该函数的驱动程序如下所示:
static void TestFill1(void)
{
cout << "***** Fill1 *****" << endl;
int i1[10];
int size = 10;
fill(i1, i1 + size, 12);
display(i1, i1 + size);
}
I am having a problem where I am given an array that is uninitialized. 我遇到了一个未初始化的数组的问题。 Previously in the assignment I was going through the array until the end.
在以前的作业中,我要遍历数组直到最后。 In this case I am given an uninitialized array which makes my T *end the same as T *left.
在这种情况下,我得到一个未初始化的数组,这使我的T * end与T * left相同。 I'm not familiar with a way to go through the passed in array.
我不熟悉通过传入数组的方法。
I was trying something that looked like this: 我正在尝试看起来像这样的东西:
template <typename T>
void fill(T *left, T *end, T fill)
{
int i = sizeof(*left) / sizeof(*(left + 0));
while(*(left + i) != *end)
{
*(left + i) = fill;
++i;
}
}
I'm not allowed to use subscripts or for loops for this assignment also, #include is off limits same with std::vector. 我也不允许为此任务使用下标或for循环,#include与std :: vector的限制相同。
The variable i
, which represents the offset with respect to the first element, should start at zero: 代表相对于第一个元素的偏移量的变量
i
应该从零开始:
int i = 0;
The loop condition is checking whether the value of the array element is equal to the value of the array element at the end. 循环条件是检查数组元素的值是否最后等于数组元素的值 。
while(*(left + i) != *end)
The correct version is the following: 正确的版本如下:
while(left + i != end)
which checks if the pointer (left + i)
has reached the end. 它检查指针
(left + i)
是否到达末尾。
Your statement 您的声明
int i = sizeof(*left) / sizeof(*(left + 0));
might not do, what you think it does. 可能不会,您认为会做。
The sizeof()
function doesn't work on plain pointers the same way as for array declarations: sizeof()
函数不适用于普通指针,而不适用于数组声明:
size_t s = sizeof(*left); // Will evaluate to sizeof(T)
while 而
int i1[10];
size_t s = sizeof(i1); // Will evaluate to sizeof(int) * 10
Your code can be simply fixed as follows: 您的代码可以简单地固定如下:
template <typename T>
void fill(T *left, T *end, T fill) {
T* cur = left;
while(cur < end) {
*cur = fill;
++cur;
}
}
http://www.cplusplus.com/reference/vector/vector/assign/ http://www.cplusplus.com/reference/vector/vector/assign/
#include <vector>
int main ()
{
std::vector<int> first;
first.assign (10,12); // 10 ints with a value of 12
return 0;
}
This is how real men do it ™. 这就是真正的男人™。 lol sorry I couldn't resist.
大声抱歉,我无法抗拒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.