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. 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. 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.
The variable i
, which represents the offset with respect to the first element, should start at zero:
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.
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:
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/
#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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.