Register to reply

C++ Vectors

by Peter P.
Tags: vectors
Share this thread:
Peter P.
May10-12, 09:01 PM
P: 24
I decided to make the switch from C to C++ and I'm having trouble with vectors. In C, I prefer to use dynamically allocated arrays when doing multidimensional arrays. But in C++, I know that there is the new function which replaced malloc. I read that when dealing with multidimensional arrays in C++, ideally a vector would be used.

So my question is, can someone just provide a quick run through of creating a 2D vector, changing the size of the vector, and then deleting it? Thank you in advance, any help is much appreciated.
Phys.Org News Partner Science news on
Final pieces to the circadian clock puzzle found
A spray-on light show on four wheels: Darkside Scientific
How an ancient vertebrate uses familiar tools to build a strange-looking head
May10-12, 09:15 PM
jtbell's Avatar
P: 11,862
See the following thread for an example:

One way to change the number of rows in the example linked above:
mymatrix.resize (numrows_new);
If this adds new rows (i.e. you increase the size), they'll be empty (zero length). If you want the new rows to have the same size as the existing ones:
mymatrix.resize (numrows_new, vector<double>(numcols));
In either case, if you decrease the number of rows, they're "chopped off" the end (bottom) of the matrix.
To change the number of columns, you have to change the size of each row:

for (int row=0; row<numrows; row++)

Register to reply

Related Discussions
Unit tangent vectors, Normal vectors, and Gradients Calculus & Beyond Homework 0
Linear Algebra - Use angles between vectors to find other vectors Calculus & Beyond Homework 4
Find unknown constant of two vectors to make vectors perpendicular to each other? Calculus & Beyond Homework 8
Vectors: Given two vectors, find a vector that bisects the angle between the two give Calculus & Beyond Homework 10
Position Vectors, Velocity Vectors, and Acceleration Vectors Introductory Physics Homework 3