I'm having trouble understanding what an internal array means. I have an assignment that ask to implement a standard queue class using internal array and set the array to 12. Is internal array another word for dynamic array, static array, ...? What is internal array? Also, what is a fixed size array inside object. This is on c++.
I thought is was asking to use a static array, fixed size array and pass by reference. As they are many ways to write a queue, just not sure which one does internal array falls under
cont int capacity = 12;
typeddef int element;
class Queue
{
public:
...
void add(const element &value);
private:
...
element myArray[capacity];
}
Now I'm being told by a classmate that it means a fixed size array inside object.
public class StandardQueue
{
private Array _array = new Array(); // This is the encapsulated member
public void WorkWithArray()
{
// Work with the array here
}
}
In this example the member called _array is only accessible from within the class StandardQueue. This means that if you create an instance of StandardQueue you would be able toa ccess function WorkWithArray but not _array. All access to _array must happen from within the class (e.g. inside the functions).
Related
I have a shared array, it is something like that
class Array
{
public:
// basic array opertion like resize, operator[], etc, like std::vector
private:
int size;
std::shared_ptr<int> data;
};
It do the shallow copy in copy constrcutor and copy assigen operator.
The memory of Array is controlled by std::shared_ptr to ensure no memory leak can happen.
Now I have a class, ArrayContainer , it have Array as the member.
I need let others access the class member. but I do not want others change it. My design is follow, but it is not good.
class ArrayContainer
{
public:
void calculation()
{
// do some operation on array ...
}
// it is not a safe interface, althogh const, others still can change the member
const Array &getArray() const
{
return this->array;
}
private:
Array array;
};
Using my interface, one may access the member in ArrayContainer by follow ways.
// example 1: safe use array
ArrayContainer container;
const Array &array = container.getArray();
// follow using array will not influence the member in user.
// example 2: may be not safy use array
ArrayContainer container;
Array array = container.getArray();
// follow using array may modify the array in container, it is not safe.
My problem is: I do not want to other's may change the member in ArrayContainer. What is a elegant way to access a shared array in class with safety?
Thanks for your time.
I don't understand why you are using std::shared_ptr, since you want memory leak to not happen.
I suppose you are using std::shared_ptr<int[]> data, and not std::shared_ptr<int> data;
I guess enough for you to use std::unique_ptr, and don't share your memory.
Anyway you need to add copy constructor to full copy array data, because in this case
ArrayContainer container;
Array array = container.getArray();
will be called copy constructor
You can do it like below
Array(const Array& array) {
for (int i = 0; i < array.size; ++i) {
data.get()[i] = array.data.get()[i];
}
}
I would like to know, if I have a class with an array attribute whose size is not the same for all instances :
class myObject{
private:
int size;
int* array;
// other methods/attributes
};
Is it obligatory allocated using new ?
explicit myObject(int size = 0):size(size){
array = new int[size];
}
Even if in the main(), I always use constant parameters to create the instances of the class ? (Meaning I know every array size at compile time).
int main{
myObject object (5);
return 0;
}
Apparently something like :
private:
int size;
int array[size];
wont work, no ?
That means that array attribute whose size are not constant of the class are obligatory on the heap ?
Thank you for your answers,
That class contains no array. What you called array is a pointer; you cannot store any ints in it. If you really do just store a pointer, you'll have to allocate the memory yourself somehow; it can't magically appear. You'll also have to deallocate it yourself, and make sure that copying and assigning myObject objects doesn't cause any issues.
However, it's unlikely that a pointer is really the best way to do things. The standard library provides the std::vector class template which lets you use almost exactly the syntax you want:
class myObject {
std::vector<int> vector;
public:
myObject() {};
explicit myObject(std::size_t n) : vector(n) {}
};
With this in place you can create myObjects and they'll have the right amount of storage ready for them. It'll likely be dynamically allocated using operator new[], just like if you'd do it manually, but you don't have to worry about copying or deleting it.
int main() {
myObject a; // default-constructed, vector is empty.
myObject b(10); // std::size_t constructor, vector has 10 elements.
} // scope exit, b and a destroyed.
You can use the vector member much like if it was an array; the only thing it does not support is implicit decay to pointer, but the data member function makes up for even that.
As an alternative, if you always know the size at compile-time you can change the class into a class template and make the size a template parameter:
template<std::size_t N>
class myObject{
std::array<int, N> array;
// other methods/attributes
};
However, note that you now cannot use myObject<10> to a function expecting myObject<20>.
It is unlikely that you want more control than the above possibilities provide -- std::vector can be given an allocator, so it can do almost all work for you -- you could use std::unique_ptr<int[]> and make_unique together to make things work for you. However, if you need this kind of power, you probably know it yourself.
As a closing note, if you're just learning C++ and your book doesn't cover std::vectors somewhere early on, perhaps it's best to get a different book; they're one of the most commonly-useful data structures in the standard library and definitely not something to be left in an appendix.
If you need a variable sized array as a member of a class, don't use built-in arrays directly. Instead, use std::vector<T>, e.g.:
class myObject {
std::vector<int> array;
public:
explicit myObject(int size = 0): array(size){}
};
You can get the std:vector<int>'s size using array.size(), i.e., there is no need to store the size separately. Also, the content is automatically default initialized.
Let's say I have a class that includes an array of some struct, and a pointer to that array.
struct Box {
//stuff
};
class Foo {
private:
Box *boxPtr //pointer to an array of Box structs
int max; //the size of the partially filled array
int boxCounter; //the current number of non-NULL elements in the array
public:
Foo(); //constructor
Foo(const Foo &obj); //copy constructor
~Foo(); //destructor
bool newBoxInsert(Box newBox){
//adds another Box to my array of Box structs
boxCounter++;
}
//etc
};
and in my int main(), I somehow must create a brand new object of class Foo.
I'm going to need to partially fill that array of indeterminate size, whose pointer is boxPtr.
How would I go about initializing that array? Should the constructor do it? Or should I let newBoxInsert handle it?
In either case, how would I achieve that? I'm guessing I would have to dynamically allocate the array. If that's the case, then it's good to have the pointer as a class member... right?
For example, when adding the very first element to my array, should I use
boxCounter = 1;
boxPtr = new Box[boxCounter];
then continue on to keep adding elements to the array?
Perhaps this is just better done with vectors. They're much more... flexible (?) when adding elements. Can vectors contain structs as elements?
[/n00b]
private:
Box *boxPtr
replace this by:
private:
std::vector<Box> mbox;
It saves you all the manual memory management. And you are less likely to go wrong.
Yes, std::vector can contain structs as elements. In fact it is a template class so it can store whatever data type you want.
In C++ if you need dynamic array, the simplest and most obvious choice us std::vector.
I want to statically allocate the array. Look at the following code, this code is not correct but it will give you an idea what I want to do
class array
{
const int arraysize;
int array[arraysize];//i want to statically allocate the array as we can do it by non type parameters of templates
public:
array();
};
array::array():arraysize(10)
{
for(int i=0;i<10;i++)
array[i]=i;
}
main()
{
array object;
}
If your array size is always the same, make it a static member. Static members that are integral types can be initialized directly in the class definition, like so:
class array
{
static const int arraysize = 10;
int array[arraysize];
public:
array();
};
This should work the way you want. If arraysize is not always the same for every object of type array, then you cannot do this, and you will need to use template parameters, dynamically allocate the array, or use an STL container class (e.g. std::vector) instead.
It has to be done using template parameters, otherwise sizeof(array) would be different for every object.
This is how you would do it using template parameters.
template <int N>
class array
{
int data[N];
// ...
};
Or, you could use an std::vector if you don't mind dynamic allocation.
C++ doesn't allow variable-length arrays (i.e. ones whose sizes are not compile-time constants). Allowing one within a struct would make it impossible to calculate sizeof(array), as the size could differ from one instance to another.
Consider using std::vector instead, if the size is known only at runtime. This also avoids storing the array size in a separate variable. Notice that allocating from heap (e.g. by std::vector) also allows bigger arrays, as the available stack space is very limited.
If you want it a compile-time constant, take a template parameter. Then you should be looking for Boost.Array, which already implements it.
The array size must be a compile time constant. You are almost there, you just need to initialize the const and make it a static as well. Or, use a dynamic array or a vector.
EDIT: note about this answer: This is most likely the wrong way to do this for your situation. But if you really need it to be an array (not a vector or whatever) and you really need it to be dynamically allocated, do the following:
class array
{
int *p_array;
public:
array(int size);
};
array::array(int size)
{
p_array = malloc(size * sizeof(int));
}
Just make sure you clean up (IE free p_array in your descructor)
This problem involved me not knowing enough of C++. I am trying to access a specific value that I had placed in the Heap, but I'm unsure of how to access it. In my problem, I had placed a value in a heap from a data member function in an object, and I am trying to access it in another data member function. Problem is I do not know how, and I had searched examples online, but none were what I needed as they were all in int main() and were not specifically what I needed.
In the first data member function, I declare the value I want to be sent to the Heap;
Here's an example of what my first data member function.
void Grid::HeapValues()
{
//Initializing Variable
value = 2; //The type is already declared
//Pointers point a type towards the Heap
int* pValue = new int;
//Initialize an a value of in the Heap
*pValue = value;
}
And in data member function This is what want:
void Grid::AccessHeap()
{
//Extracting heap:
int heap_value = *pValue; //*pValue does not exist in this function
cout << heap_value; //Delays the value 2, which is found
//in the first data member function
}
I feel foolish for asking, but I am unable to find the answers and do not how. Does anyone know how to access a value from the heap in a simple way? And I would need it to be able to access in more then two data member function.
pValue needs to be a member-variable of the class Grid.
class Grid
{
private: int* pValue;
public: void HeapValues();
void AccessHeap();
};
Now the member-variable pValue is accessible from any member-function of Grid.
Don't forget to delete your pointer in the destructor when you are done. For more information visit:
http://www.cplusplus.com/doc/tutorial/variables.html <-- Variable scope
http://www.cplusplus.com/doc/tutorial/pointers.html <-- Pointers
http://www.cplusplus.com/doc/tutorial/dynamic.html <-- Dynamic memory
Like Aaron said you can make the value a member of your Grid class. In this case though there is no need for it to be a pointer to an int.
class Grid
{
private:
int value;
public:
void HeapValue();
void AccessHeap();
};
The value will be stored as part of the object wherever it is instanciated. You can make it on the stack or the heap, it doesn't matter. For simple values like the built in types and Objects that will be owned by the instance of the class it is unnecessary to allocate them using new. This way you don't need to worry about cleaning up with the delete operator in the Grid destructor, just make sure you dispose of the owning Grid instance properly ;-)
Of coarse there are exceptions to this that you will learn as you delve more into C++, but for your example the above will be fine.
Why do you want it on the heap? If you add it as part of the class then it will be in the same place the class is, possibly on the stack or in global memory. Perhaps you want to have a variable size to your integer pointer? In that case, then you need to be sure to deallocate the memory when you are done with it.
The problem with stuff on the heap is finding it. There is no accessing it by name, unless you add a mechanism for that. Somehow you need to communicate the location to whatever code needs to access it. In this case, it looks like you only need access within the Grid class, so it is easy. Just make it a member variable like Aaron indicates. You might end up with something like:
class Grid
{
protected:
int* pVals;
public:
Grid() pVals(NULL) { }
~Grid() { delete [] pVals; }
void HeapValues() {
pVals = new int[getHeapValuesSize()];
pVals[0] = 1; // ...
}
void AccessHeap() {
cout << pVals[0]; // ...
}
(On a side note, you appear to be using the phrase "data member function" when you mean "member function". "Data member" refers to member data of a class, like pVals, but I'm not sure what "data member function" would mean.)