The situation is that I have an array of items, and the items have an array inside. However, I want to make the array inside of variable length at declaration time, yet resizable at compile time.
So I would want something like:
class2<16>[] = new class2<16>[2048*1024];
Or whatever. Hopefully you get the idea.
Obviously making it have fixed array inside is easy, but the problem is the array can be HUGE so I don't want to have 2048*1024 calls to new, so I definitely don't want class2 to call any new or delete methods.
Is this even possible?
You can create a template parameter for your internal array-size. For example:-
template<int siz>
class Item{
int arr[siz];
};
int main() {
Item<15> items[10];
return 0;
}
std::tr1::array (addition to standard library in C++0x) and boost::array already exist, taking two template parameters: the type and count of items:
std::tr1::array<int, 16> something;
You can have any number of those arrays at run-time with the std::vector container:
std::vector<std::tr1::array<int, 16> > lots_of_arrays(2048*1024);
Only one dynamic allocation involved here.
Related
For my project I need to store pointers to objects of type ComplicatedClass in an array. This array is stored in a class Storage along with other information I have omitted here.
Here's what I would like to do (which obviously doesn't work, but hopefully explains what I'm trying to achieve):
class ComplicatedClass
{
...
}
class Storage
{
public:
Storage(const size_t& numberOfObjects, const std::array<ComplicatedClass *, numberOfObjects>& objectArray)
: size(numberOfObjects),
objectArray(objectArray)
{}
...
public:
size_t size;
std::array<ComplicatedClass *, size> objectArray;
...
}
int main()
{
ComplicatedClass * object1 = new ComplicatedClass(...);
ComplicatedClass * object2 = new ComplicatedClass(...);
Storage myStorage(2, {object1, object2});
...
return 0;
}
What I am considering is:
Using std::vector instead of std::array. I would like to avoid this because there are parts of my program that are not allowed to allocate memory on the free-store. As far as I know, std::vector would have to do that. As a plus I would be able to ditch size.
Changing Storage to a class template. I would like to avoid this because then I have templates all over my code. This is not terrible but it would make classes that use Storage much less readable, because they would also have to have templated functions.
Are there any other options that I am missing?
How can I pass and store an array of variable size containing pointers to objects?
By creating the objects dynamically. Most convenient solution is to use std::vector.
size_t size;
std::array<ComplicatedClass *, size> objectArray;
This cannot work. Template arguments must be compile time constant. Non-static member variables are not compile time constant.
I would like to avoid this because there are parts of my program that are not allowed to allocate memory on the free-store. As far as I know, std::vector would have to do that.
std::vector would not necessarily require the use of free-store. Like all standard containers (besides std::array), std::vector accepts an allocator. If you implement a custom allocator that doesn't use free-store, then your requirement can be satisfied.
Alternatively, even if you do use the default allocator, you could write your program in such way that elements are inserted into the vector only in parts of your program that are allowed to allocate from the free-store.
I thought C++ had "free-store" instead of heap, does it not?
Those are just different words for the same thing. "Free store" is the term used in C++. It's often informally called "heap memory" since "heap" is a data structure that is sometimes used to implement it.
Beginning with C++11 std::vector has the data() method to access the underlying array the vector is using for storage.
And in most cases a std::vector can be used similar to an array allowing you to take advantage of the size adjusting container qualities of std::vector when you need them or using it as an array when you need that. See https://stackoverflow.com/a/261607/1466970
Finally, you are aware that you can use vectors in place of arrays,
right? Even when a function expects c-style arrays you can use
vectors:
vector<char> v(50); // Ensure there's enough space
strcpy(&v[0], "prefer vectors to c arrays");
I have this method:
void createSomething(Items &items)
{
int arr[items.count]; // number of items
}
But it's throwing an error:
expression must have a constant value
I found just this solution:
int** arr= new int*[items.count];
so I'm asking is there a better way how do handle this?
You can use a std::vector
void createSomething(Items &items)
{
std::vector<int> arr(items.count); // number of items
}
The reason your first method won't work is that the size of an array must be know at compile time (without using compiler extensions), so you have to use dynamically sized arrays. You can use new to allocate the array yourself
void createSomething(Items &items)
{
int* arr = new int[items.count]; // number of items
// also remember to clean up your memory
delete[] arr;
}
But it is safer and IMHO more helpful to use a std::vector.
Built in arrays & std::array always require a constant integer to determine their size. Of course in case of dynamic arrays (the one created with new keyword) can use a non-constant integer as you have shown.
However std::vector (which of course internally a dynamic array only) uses a is the best solution when it comes to array-type applications. It's not only because it can be given a non-constant integer as size but also it can grown as well as dynamically quite effectively. Plus std::vector has many fancy functions to help you in your job.
In your question you have to simply replace int arr[items.count]; with :-
std::vector<int> arr(items.count); // You need to mention the type
// because std::vector is a class template, hence here 'int' is mentioned
Once you start with std::vector, you would find yourself preferring it in 99% cases over normal arrays because of it's flexibility with arrays. First of all you needn't bother about deleting it. The vector will take care of it. Moreover functions like push_back, insert, emplace_back, emplace, erase, etc help you make effective insertions & deletions to it which means you don't have to write these functions manually.
For more reference refer to this
It's possible to create an array like this - if size is defined before arr.
const int size = 5;
int arr[size];
But it's not possible, when size and arr are inside object or struct:
struct A{
A(int s) : size(s)
{}
const int size;
int arr[size]
};
A(5);
Why is it so? It's seems kinda illogical, because in both cases size of array is known in compilation time.
It's seems kinda illogical, because in both cases size of array is known in compilation time.
The compiler cannot distinguish between your example and this:
int i = std::rand(); // not a compile time constant
A a(i);
On the other hand, it needs to know the size of the array at compile time. Two instances of A cannot have different size. So the size of the array cannot depend on something that can be set at runtime.
On the other hand, C++11 provides constexpr, which allows you to propagate compile-time constants through expressions and lets you use these to initialize arrays.
in both cases size of array is known in compilation time.
Nope, a const class member can be set at run-time.
In fact, even a non-member doesn't always work:
int x;
cin >> x;
const int y = x;
int z[y]; //ILLEGAL
Just use a std::vector.
When the compiler compiles A, there is in fact no guarantee that it is a compile-time argument. It just happens to be one. I could equally do
int main() {
std::cin >> i;
A(i);
}
If you want to pass it a constexpr argument, you will need to use a template. Else, you will need to use a run-time container like std::vector.
You should use std::vector<int> instead of raw arrays if you want a dynamically resizeable array.
You cannot do what you're trying to do inside the class or struct because your size member has no defined value.
Because in C++ when you initialize a C-style array with a size argument, the size must be a compile-time integral constant.
Otherwise the compiler doesn't know how big to make the variable when compiling.
If you don't like this, you should be using vector anyway.
In second case, if you take into consideration just class definition array size is not known in compilation time.
if making such classes was allowed you could write
A(5);
A(6);
that would be objects of different size, that would break alot, for example it would not be possible to keep such objects in the same array. It would be logical to say that those objects have different type, and that would be possible if you make your class template and pass size as template parameter.
if you want to use arrays of different size use std::vector or templates.
You need to dynamicly allocate the memory from your heap if it is not known before compile time.
int* arr = new int [size];
If you do not need the memory anymore you should delete the array.
delete[] arr;
And also as Tony said, it is better to use standart libary vectors
Coming from a PHP background, I'm trying to learn C++, since I find it an interesting language. As a practice I want to create a simple Vector class using templates, which is not to hard. However, I run into one problem.
I have created the following template class:
template <typename T>
class Vector
{
public:
Vector(int length);
~Vector(void);
int getLength();
T& operator[] (const int index);
private:
T *_items;
int _count;
};
template <typename T>
Vector<T>::Vector(int length)
{
_items = new T[length];
_count = length;
}
template <typename T>
T& Vector<T>::operator[]( const int index )
{
if (index >= getLength() || index < 0)
throw exception("Array out of bounds.");
return _items[index];
}
All functions are implemented, but they're not relevant to my question, so I haven't copied them here.
This class works as expected, with one exception:
If I want to create a vector of array's, it doesn't work.
e.g.:
Vector<int[2]> someVector(5);
What I obviously want is that the _items property of the vector class will be an int[5][2]. However, since the compiler replaces the 'T' with 'int[2]', the _items property will be int[2][5] (or at least, that's what I understood from debugging, please correct me if I'm wrong). As a result, the [] operator doesn't work correctly anymore, and therefore this whole class is useless for arrays.
Is there a way to solve this problem, so that this class also works for arrays? And if that's not possible, is there a way to prevent this class being initialized with arrays?
Edit: Thanks for all your responses so far. However, I might have been not entirely clear with my question. First of all, I created this class to get used to c++, I know there is a std::vector class, and I also now that it's better to use a vector of vectors. That's not really the problem. I just want to understand templates better, and c++ in general, so I want to know how to deal with this type of problems. I want to be able to create classes which don't make the program crash. If I, or someone else, would use this class right now and tried to use primitive arrays instead of vectors for this class, at some point the program will crash since the array is wrong (Vector(y) becomes int[x][y] instead of int[y][x] internally). So I want a solution which either creates the correct array, or prevents the vector being initialized with arrays at all.
Quite simply, don't ever use the in-built primitive arrays. For anything. They suck, tremendously. Always use a class wrapper such as boost::array, if you don't have TR1 or C++0x both of which also provide an array class. A Vector<boost::array<int, 2>> will trivially compile.
Why not use primitive arrays?
They have hideous implicit conversions to pointers, forget their size at the drop of a hat, aren't first-class citizens (can't assign to them, for example), don't check their bounds, for example. boost::array<int, 2> is exactly a primitive array without crappy conversions, is fully generic- for example, your Vector template works fine with a boost::array<int, 2> off the bat, and it can do bounds checking in the at() function.
I'm not suggesting using a dynamic array instead. boost::array is not a dynamically sized array. It is a constant size, value type array, that will not convert to a pointer, it has functions for use in the Standard library like begin, end, size, and it can be treated like any other type- unlike arrays, which have a dozen special rules- as you've found out.
I see a few things wrong with this.
If you are making a generic vector class, why deal with a vector of arrays rather than a vector of vectors?
Rather than defining a vector of type int[2], try making a vector of vectors of size 2 with something like this:
Vector<Vector<int>> vector(5);
for (int i = 0; i < 5; i++)
{
vector[i] = Vector<int>(2);
}
Rather than using a constant sized array, try using a pointer.
Rather than using a pointer to arrays of size 2, use a pointer to a pointer, and allocate two spaces for that pointer. Pointers are a lot easier to deal with in C++ because you can simply pass the address of the pointer rather than having to copy the entire array. It's generally very bad form to pass arrays.
Add a default parameter to your constructor
Rather than declaring the constructor with Vector(int length);, try using Vector(int length = 0); so that if the user doesn't specify a length it will default to a size of zero.
Finally, are you aware that there is in fact an std::vector, or are you aware of this and simply trying to replicate it? Templates are known to be one of the hardest subjects of C++, good luck!
The condition must say index >= getLength(), because getLength() is not an allowed index value too (the first element's index is 0, the last's is getLength()-1)
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)