I have a vector of size lets say 4:
vector <double> example;
example.push_back(3.0);
example.push_back(10.1);
example.push_back(33.1);
example.push_back(23.3);
so I have [3 10.1 33.1 23.3];
If I know I have a square matrix (i.e. sizes can only be 4, 9, 16, 25, 36, 49...)
How do I know the # of rows which is the same as the number of columns in c++??
so I am doing
int size, col, row;
size = example.size();
row = col = sqrt(size);
Is there other a faster way??
A two-dimensional array allocated as contiguous locations will be faster than a vector
of vector
s or an array of vector
s. A vector has a slight disadvantage in that functions must be called to access the vector (although the compiler may optimize these out).
For example:
enum {MATRIX_SIZE = 4};
// Define a square matrix of integers
int matrix[MATRIX_SIZE * MATRIX_SIZE];
// Set value at row: 3, column 2 to 64:
unsigned int row = 3;
unsigned int column = 2;
matrix[row * MATRIX_SIZE + column] = 64;
Using vectors has a slight overhead.
The question to answer is whether the difference in performance between arrays and vectors is worthwhile. The person hours in maintenance and development may outweigh the benefit in performance (i.e. a slower but correct and released applications may be worth more than a faster application that is released much later to the market place or consumers).