Reputation: 5933
Is there anyway to make a 1D dynamic and continuous array using C++11?
I will take in the size of the array via stdin
and once it's created it won't need to be resized.
Right now I am using a 1D vector of enums, and my biggest performance issue is the vector [] operator.
If it can't be done in C++, I am open to ways of doing it with malloc
and C, just please note the best way to delete
it.
Edit: Didn't realize vectors were night and day with debug and release. I reran callgrind with -O3 and now the issue is ostream not vectors - thanks to everyone who made me second guess myself before I rewrote it all using arrays when not needed.
Upvotes: 0
Views: 557
Reputation: 83283
If you are using C++, using malloc
is probably a poor (inferior) idea.
int length;
cin >> length;
MyType * array = new MyType[length];
Then to delete,
delete[] MyType;
Upvotes: 0
Reputation: 765
int size = 10;
std::unique_ptr<int[]> a(new int[size]);
Follows RAII (that is array is autodestructed)
However I don't think vector [] operator should be performance issue. In debug compilation it may be checked, however in release it should not.
In MSVC there is feature called checked iterators which may "kill" performance. However you're able to switch this feature off (just google it)
Upvotes: 3
Reputation: 5238
std::vector
has enough performance to use in production. It is used for solving problems on programming contests. Maybe, you forget to compile into release?
Also, you can use new
and delete
operators.
To free allocated memory use free(void *ptr)
function.
Upvotes: 2
Reputation: 63737
You can always dynamically create contiguous homogeneous storage of a certain type from the heap using the new operator
Type *pType = new Type[size](initial_value)
In Order to delete the storage, you need to explicitly invoke the array delete operator
delete[] pType
But, when you say, and my biggest performance issue is the vector [] operator.
, I doubt. Did you profile the retail version of your code? How do you know the vector subscript is your performance bottleneck?
Upvotes: 3
Reputation: 46405
In C you create a 1-D array with
int *ptr=NULL;
int num_elements = 0;
printf("how many elements?\n");
if(scanf("%d", &num_elements)==1) {
ptr = malloc(sizeof(int)*num_elements);
if(ptr == NULL) {
printf("unable to allocate %d elements\n", num_elements);
exit 0;
}
}
and when you're done, you call
free(ptr);
Make sure you call it only once! Some people will do
if( ptr != NULL ) {
free(ptr);
ptr = NULL;
}
as defensive coding - prevents accidentally freeing it twice.
Upvotes: 0