I need to do the equivalent of the following C# code in C++
Array.Resize(ref A, A.Length - 1);
How to achieve this in C++?
You cannot resize array, you can only allocate new one (with a bigger size) and copy old array's contents.
If you don't want to use std::vector (for some reason) here is the code to it:
int size = 10;
int* arr = new int[size];
void resize() {
size_t newSize = size * 2;
int* newArr = new int[newSize];
memcpy( newArr, arr, size * sizeof(int) );
size = newSize;
delete [] arr;
arr = newArr;
}
code is from here http://www.cplusplus.com/forum/general/11111/.
new and the delete, an exception is thrown? -1 for suggesting manual resource management to a newbie. (If you want to make this safe, you will need a smart pointer. If you add a few more utility functions, you'll arrive at std::vector.)new and delete this means you're in real trouble, and you cannot really do anything in the resize function, you shouldn't catch exception there (maybe just to rethrow some more informative one) and let the caller to handle it.The size of an array is static in C++. You cannot dynamically resize it. That's what std::vector is for:
std::vector<int> v; // size of the vector starts at 0
v.push_back(10); // v now has 1 element
v.push_back(20); // v now has 2 elements
v.push_back(30); // v now has 3 elements
v.pop_back(); // removes the 30 and resizes v to 2
v.resize(v.size() - 1); // resizes v to 1
ref in iJeeves' code would not have been necessary.std::array won't help here either: Yes, it's on the stack, but it's not resizable.)Raw arrays aren't resizable in C++.
You should be using something like a Vector class which does allow resizing..
std::vector allows you to resize it as well as allowing dynamic resizing when you add elements (often making the manual resizing unnecessary for adding).
Array.Resizeis actually allocating a new array and reassigning the variable - hence the need forref. The original array does not change.