I'm trying to set all the elements of my array to 0 but nothing seems to be working. Could greatly use some help. Thanks!
.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#ifndef ServerGroup_h
#define ServerGroup_h
class ServerGroup
{
public:
ServerGroup(constint&);
private:
int *servers;
};
#endif
.cpp
1 2 3 4 5 6 7 8 9 10
ServerGroup::ServerGroup(constint& numArray)
{
size = numArray; // number of elements in the array
servers = newint [numArray]; // pointer to numArray
size = numArray; // size = elements in the array
}
I want to set each element of the array in servers to 0 based on what is passed into size by numArray.
Thanks and we can't use vector yet because our textbook hasn't covered vectors yet. We have only just been introduced to "new". Ah and yes sorry about lines 3 and 7 being the same. I was playing around with my code and didn't realize I copied and pasted something twice in different places. Good eye!
Would newint[numArray]() be doing the same thing as this for loop?
Basically I just want to set servers to 0.
1 2 3 4 5 6 7 8 9
ServerGroup::ServerGroup(constint& numArray) // set # elements in dynamic array
{
servers = newint[numArray];
size = numArray;
for(int i = 0; i < size; i++)
{
servers[i]=0;
}
}
vs
1 2 3 4 5
ServerGroup::ServerGroup(constint& numArray) // set # elements in dynamic array
{
size = numArray; // num elements in array
servers = newint [numArray]();
}
yes, servers = newint[numArray](); sets all servers to 0. It's when you need initial values other than zero when you need a loop (or, more typically, a vector)
well, in the case of you're using a simple array, you can use the fill function contained in the algorithm library, or simply you can use the iterator method -- for(i = 1 -- N) arr[i] = 0, you can create a new instance of the array, or you can use the data structure vector<Object>
the structure of fill is just like this:
fill(array+1, array+N+1, 0);