Cannot access element of 2d heap vector using operator[] - c++

I have a 2d vector that needs to be allocated on the heap and am using the below line of code to declare and size it.
vector<vector<double>> *myArray = new vector<vector<double>>(x, vector<double>(y));
where x and y are the number of rows and columns respectively.
When I try to access an element of the vector using myArray[0][0] = 3.0;, I get the following error,
error: no viable overloaded '='
myArray[0][0] = 3.0;
I would appreciate any help in figuring this out.
Notes:
The number of rows and columns needs to be dynamic, hence myArray is on the heap.
The array needs to be resizable, which is why I am using std::vector.
I understand that I can create a vector of vectors (number of rows) and then in a for-loop resize each row element to the required number of columns. What I do not understand is why the above code does not work since as far as I know it should perform the same function.

For some strange invalid reason, you are using a pointer to a vector. Since operator[] works with pointers, when you do
myArray[0][0] = 3.0;
you are actually accessing a vector<double>, not a double, because myArray[0] gets you a vector<vector<double>>.
The obvious fix is not to use a pointer in the first place:
vector<vector<double>> myArray(x, vector<double>(y));

must be:
(*dataArray)[0][0] = 3.0

Related

Initialize a 2d array with unknown first dimension size in C++

Say I need a 2d array, first dimension size set at runtime, and second dimension size is set to 5 at compilation time.
Since we can do this to initialize a 1d array with unknown size
int* arr;
arr = new int[12];
I would like to make the following code work
int* arr[5];
arr = new int[12][5];
Notice:
I need the second dimension set to 5, not first dimension. So I need to be able to do arr[11][4] but not arr[4][11].
I know I can make arr an int** and then assign a 2d array to arr, so please avoid such answer.
I know I can use STL containers such as vector, so please avoid such answer.
You can write:
int (*arr)[5];
arr = new int[12][5];
Then you can access elements such as arr[11][4]. But not arr[12][5] as you suggest in the question, arrays are zero-indexed and the maximum element index is one less than the dimension.
All dimensions except the innermost must be known at compile-time. If the 5 is actually meant to represent a runtime value then you cannot use C-style arrays for this task .
NB. Consider using unique_ptr for safe memory management. The code would be auto arr = std::make_unique<int[][5]>(12);.

Does an array of vectors form a 2D vector?

Does the following statements form a 2D vector?
Also mention the dimensions of the vector if it does. Is there another way of declaring a global 2D vector?
Statements:
vector<int> *adj;
adj = new vector<int>[number_of_nodes];
The above statements have been used for declaration of a global adjacency matrix for a graph.
It seems the question isn't clear to much of you. I want to declare a global adjacency list using vectors such that I can use direct addition of edges in graph like v[a].push_back(b). For that, I have to specify first dimension of vector while declaring which I don't have until the main is executed.
No, but it gives similar behaviour. So what you have created is a pointer to an array of vectors. So you will end up with this:
adj[0] = []
adj[1] = []
...
adj[number_nodes] = []
and doing a push_back is a legitimate way to add to the vectors:
adj[0].push_back(some_num) --> adj[0] = [some_num]
But this is a terrible way to approach this! Why?
You are using raw memory that you will have to manage and make sure you delete.
You cant use any of the awesome std::vector functionality on the first dimension of the matrix.
There is no good way to figure out the size of the vector unless you know about the variable number_of_nodes.
... A long list, but you get it.
You can already see that a std::vector can be used as a 1D matrix. So use 2 vectors:
std::vector<std::vector<int>> Matrix2D;
If you need an initial size in some dimension then you can do this:
std::vector<std::vector<int>> Matrix2D(number_of_nodes, std::vector<int>());
Or this:
Matrix2D.resize(number_of_nodes);
Or if that size is fixed at compile time then you could even do this:
const int number_of_nodes = 10;
std::array<std::vector<int>, number_of_nodes> Matrix2D;
Or go extra big and get a library for Matrix use like Eigen.

Isolate a column of a vector in c++

I have a 2d vector of string and need to isolate out three of the columns into 3 separate 1d arrays so i can convert them to doubles and perform operations on them.
Simply using:
for (int i = 0; i < 100; i++)
{
vectorname[i][2] = arrayname[i];
}
doesn't work and I don't understand why.
Sorry im new to coding and thanks in advance.
Thanks to first reply, i don't care if i remove the data or not, i just need it so i can operate on it, my vectors are declared as:
string vectorname[101][5];
string arrayname[99];
string arrayname2[99];
string arrayname3[99];
Ok I dont have my vectorname defined as a vector, it's just a 2d string, can i extract a column from that?
Do the columns still need to remain in the 2D vector, or be pulled out completely as independent data?
If you need independent data, I would do
vector<double> col(vectorname[i]);
Then manipulate col as needed. You could even do move construction if you don't need that data in the 2D vector anymore.
I think you have actual logic problems elsewhere though. Show us your vector declarations.
EDIT: What...? You're not declaring vectors at all. You're using pure arrays. And a 2D array shouldn't be called a vector. You're confusing other programmers with your name scheme.
The proper way to declare a vector of strings is
std::vector<string> vectorname(100);
And a vector of vector of strings (a 2D vector) is
std::vector<std::vector<string>(5)> vectorname(101);
But moreover, your dimensions mismatch. Your 1D vectors need to be the same length as the given dimension of your 2D, or 5 (101?) in this case.
If you're trying to copy the values along the first dimension of values, there's no direct constructor for that. You have to manually loop from 0 to 100 and say
arrayname[i] = vectorname[i][n];
Where n is your column number.

Error: Deallocating a 2D array

I am developing a program in which one of the task is to read points (x,y and z) from a text file and then store them in an array. Now the text file may contain 10^2 or even 10^6 points, depending upon the text file user selects. Therefore I am defining a dynamic array.
For allocating a dynamic 2D array, I wrote as below and it works fine:
const int array_size = 100000;
float** array = new float* [array_size];
for(int i = 0; i < array_size; ++i){
ary[i] = new float[2]; // 0,1,2 being the columns for x,y,z co-ordinates
}
After the points are saved in the array, I write the following to deallocate the unallocated memory :
for (int i = 0; i < array_size; i++){
delete [] array[i];
}
delete [] array;
and then my program stops working and shows "Project.exe stopped working".
If I don't deallocate, the program works just fine.
In your comment you say 0,1,2 being the columns for x,y,z co-ordinates, if that's the case, you need to be allocating as float[3]. When you allocate an array of float[N], you are allocating a chunk of the memory of the size N * sizeof(float), and you will index them in the array from 1 to N - 1. Therefore if you need indeces 0,1,2, you will need to allocate a memory of the size 3 * sizeof(float), which makes it float[3].
Because other than that, I can compile and run the code without an error. If you fix it and still get an error, it might be your compiler problem. Then try to decrease 100000 to a small number and try again.
You are saying that you are trying to implement a dynamic array, this is what std::vector does and I would highly recommend that you use it. This way you are using something from the standard library that's extremely well tested and you won't run into issues by essentially trying to roll your own version of std::vector. Additionally this approach wraps memory better as it uses RAII which leverages the language to solve a lot of memory management issues. This has other benefits too like making your code more exception safe.
Also if you are storing x,y,z coordinates consider using a struct or a tuple, I think that enhances readability a lot. You can typedef the coordinate type too. Something like std::vector< coord_t > is more readable to me.
(Thanx a lot for suggestions!!)
Finally I am using vectors for the stated problem for reasons as below:
1.Unlike Arrays (not array object ofcourse), I don't need to manually deallocate unallocated memory.
2.There are numerous built in methods defined under vector class
Vector size can be extended at later stages
Below is how I used 2D Vector to store points (x,y,z co-ordinates)
Initialized (allocated memory) a 2D vector:
vector<vector<float>> array (1000, vector<float> array (3));
Where 1000 is the number of rows, and 3 is the number of columns
Once declared, values can be passed simply as:
array[i][j] = some value;
Also, at later stage I declared functions taking vector arguments and returning vectors as:
vector <vector <float>> function_name ( vector <vector <float>>);
vector <vector <float>> function_name ( vector <vector <float>> input_vector_name)
{
return output_vector_name_created_inside_function
}
Note: This method crates a copy of vector while returning, use pointer to return by reference. Even though mine is not working when I return vector by reference :(
For multi arrays I recommended use boost::multi_array.
Example:
typedef boost::multi_array<double, 3> array_type;
array_type A(boost::extents[3][4][2]);
A[0][0][0] = 3.14;

Incrementally dynamic allocation of memory in C/C++

I have a for-loop that needs to incrementally add columns to a matrix. The size of the rows is known before entering the for-loop, but the size of the columns varies depending on some condition. Following code illustrates the situation:
N = getFeatureVectorSize();
float **fmat; // N rows, dynamic number of cols
for(size_t i = 0; i < getNoObjects(); i++)
{
if(Object[i] == TARGET_OBJECT)
{
float *fv = new float[N];
getObjectFeatureVector(fv);
// How to add fv to fmat?
}
}
Edit 1 This is how I temporary solved my problem:
N = getFeatureVectorSize();
float *fv = new float[N];
float *fmat = NULL;
int col_counter = 0;
for(size_t i = 0; i < getNoObjects(); i++)
{
if(Object[i] == TARGET_OBJECT)
{
getObjectFeatureVector(fv);
fmat = (float *) realloc(fmat, (col_counter+1)*N*sizeof(float));
for(int r=0; r<N; r++) fmat[col_counter*N+r] = fv[r];
col_counter++;
}
}
delete [] fv;
free(fmat);
However, I'm still looking for a way to incrementally allocate memory of a two-dimensional array in C/C++.
To answer your original question
// How to add fv to fmat?
When you use float **fmat you are declaring a pointer to [an array of] pointers. Therefore you have to allocate (and free!) that array before you can use it. Think of it as the row pointer holder:
float **fmat = new float*[N];
Then in your loop you simply do
fmat[i] = fv;
However I suggest you look at the std::vector approach since it won't be significantly slower and will spare you from all those new and delete.
better - use boost::MultiArray as in the top answer here :
How do I best handle dynamic multi-dimensional arrays in C/C++?
trying to dynamically allocate your own matrix type is pain you do not need.
Alternatively - as a low-tech, quick and dirty solution, use a vector of vectors, like this :
C++ vector of vectors
If you want to do this without fancy data structures, you should declare fmat as an array of size N of pointers. For each column, you'll probably have to just guess at a reasonable size to start with. Dynamically allocate an array of that size of floats, and set the appropriate element of fmat to point at that array. If you run out of space (as in, there are more floats to be added to that column), try allocating a new array of twice the previous size. Change the appropriate element of fmat to point to the new array and deallocate the old one.
This technique is a bit ugly and can cause many allocations/deallocations if your predictions aren't good, but I've used it before. If you need dynamic array expansion without using someone else's data structures, this is about as good as you can get.
To elaborate the std::vector approach, this is how it would look like:
// initialize
N = getFeatureVectorSize();
vector<vector<float>> fmat(N);
Now the loop looks the same, you access the rows by saying fmat[i], however there is no pointer to a float. You simply call fmat[i].resize(row_len) to set the size and then assign to it using fmat[i][z] = 1.23.
In your solution I suggest you make getObjectFeatureVector return a vector<float>, so you can just say fmat[i] = getObjectFeatureVector();. Thanks to the C++11 move constructors this will be just as fast as assigning the pointers. Also this solution will solve the problem of getObjectFeatureVector not knowing the size of the array.
Edit: As I understand you don't know the number of columns. No problem:
deque<vector<float>> fmat();
Given this function:
std::vector<float> getObjectFeatureVector();
This is how you add another column:
fmat.push_back(getObjectFeatureVector());
The number of columns is fmat.size() and the number of rows in a column is fmat[i].size().