(C++) Initializing and Declaring elements within a Two Dimensional Vector - c++

I'm having an awkward result when I run my program after creating this 2D vector. The program actually crashes when it launches. But I'm basically trying to input a set of data for a 2D vector that is meant to retain the amount of bushels of certain crops in the first column (as ints), and then to retain the yield ratio of each crop (as an int). I haven't declared the yield ratio yet, but even if the 2nd column is left empty (in terms of each element's value) it shouldn't have a problem. Here's my code:
vector<vector<int> >crops(2, vector<int>(43));
crops[0][0]=0; //Arugula
crops[1][0]=2000000; //Beans
crops[2][0]=0; //Beets
crops[3][0]=0; //Cabbages
crops[4][0]=0; //Cammomile
crops[5][0]=0; //Carrots
crops[6][0]=0; //Catmint
crops[7][0]=0; //Celery
crops[8][0]=0; //Coriander
crops[9][0]=0; //Corn
crops[10][0]=0; //Cucumbers
crops[11][0]=0; //Eggplants
crops[12][0]=2000000; //Fennel
crops[13][0]=1500000; //Flax
crops[14][0]=0; //Garlix
crops[15][0]=0; //Greenwoad
crops[16][0]=0; //Hem
crops[17][0]=0; //Leeks
crops[18][0]=0; //Lettuce
crops[19][0]=0; //Madder
crops[20][0]=0; //Mint
crops[21][0]=0; //Mustard
crops[22][0]=5000000; //Oats
crops[23][0]=0; //Onions
crops[24][0]=0; //Parsnips
crops[25][0]=0; //Parsely
crops[26][0]=2500000; //Peas
crops[27][0]=0; //Poppy
crops[28][0]=0; //Potatoes
crops[29][0]=0; //Pumpkins
crops[30][0]=0; //Radishes
crops[31][0]=0; //Rutabagas
crops[32][0]=0; //Spinach
crops[33][0]=4000000; //Spring Barley
crops[34][0]=0; //Squash
crops[35][0]=0; //Tomatoes
crops[36][0]=0; //Turnips
crops[37][0]=0; //Vetches
crops[38][0]=0; //Weld
crops[39][0]=0; //Woad
crops[40][0]=6000000; //Barley - Winter Crop
crops[41][0]=5000000; //Mixtill - Winter Crop
crops[42][0]=4000000; //Wheat - Winter Crop
Though, I have to leave for work now, but I will be able to respond to any answers once I return tonight. Thank you for those who are trying to help! :)

Swap your subscript indices.
crops[13][0] -> crops[0][13]
When you declared
vector<vector<int> >crops(2, vector<int>(43));
You created a vector which is value-initialised with 2 vectors, each of which was value-initialised with 43 ints (meaning they are initialised to 0). There are two vectors in the outer vector so you can only do crops[0] or crops[1] without reading someone else's memory.
Alternatively, of course, you could just change the declaration to:
vector<vector<int> >crops(43, vector<int>(2));

Related

Operations with arrays

I have to code a program using C++ at university.
They asked me to type all elements of a 3x3 matrix. And all elements have to be positive. So far so good. Each row of the matrix represents the components of a R^3 vector. So there are three vectors (Three 1D arrays). I had to calculate the modulus of each vector and successfully did it.
Here comes the problem... The next step is to get which vector the largest modulus has, and return its position. All this using a function --> int largestModulus (int Modulus[3]). How can I do that? Because it is all about comparing but this time is comparing a vector, and I only know how to compare different single elements. Thanks for your help!!
In the arguments to the function,
since you're passing and receiving a 2D matrix, the parameter must be
int largestModulus (int Modulus[][3])

Eigen conservativeResize strange behavior

I am using m.conservativeResize() to do the equivalent in Eigen as the reshape function in MatLab. So let N = 3, and then...
static MatrixXd m(N*N,1);
and then I assign this matrix some values, and it looks like this:
1
1
0
1
0
1
0
1
1
and then try to reshape it...
m.conservativeResize(N,N);
So now the same values should be there, but now in N rows and N columns rather than N*N rows and one column.
However that's not what I get. The first column has the first three values in the column vector - OK so far - but then the remaining values just look like garbage values from uninitialized memory:
1 3.08116e-309 0.420085
1 -2.68156e+154 1.2461e-47
0 -2.68156e+154 0.634626
Any idea what I am doing wrong?
conservativeResize() doesn't ``move" the elements around (in other words, doesn't work like MATLABs reshape, since it performs memory re-allocation even if the initial and final sizes are the same). From the documentation:
Resizes the matrix to rows x cols while leaving old values untouched.
...
Matrices are resized relative to the top-left element. In case values need to be appended to the matrix they will be uninitialized.
These statements seem a bit confusing. What it means is the following: think about the initial matrix as a rectangle, of size A x B. Then think about the resized matrix as another rectangle of size C x D. Then mentally overlap the two rectangles, making sure the top-left corner is common to both. The common elements of the intersection are the ones that are preserved by the conservativeResize. The rest just correspond to uninitialized memory.
In case you want a true reshaping, use resize() instead (making absolutely sure that A x B == C x D, otherwise reallocation takes place and all bets are off).

How to determine if an element in a multidimensional array is empty

I am working on a magic square problem that uses a dynamic matrix of size n*n. It fills the matrix with numbers 1-n^2, and the sum of each row, column, and diagonal must be the same. One of the conditions of the algorithm is to check if an element in the matrix already had a number input in it during one of the loops. I am having problems checking if one of the elements in the matrix already had a number inputed in it, so I am wondering how to check if an element is empty.
Here is my code for that portion of the algorithm:
else if(matrix[row][col] != 0)
{
row = row + 2;
col--;
}
For some reason it triggers this if statement on the 5th iteration of the encompasing loop. I have worked it out on paper using the algorithm for a magic square, and the 5th iteration of the loop brings it to an empty element in the matrix. I thought that if an element is empty it holds the value 0? I appreciate any help as I am very confused. Thank you.
Array's in C and C++ are not empty by default. You need to explicitly set the elements to 0 or create the array in such a way that they are initialized to 0.
What you are facing is Undefined Behavior. The uninitialized array has some random(read garbage) values and accessing those results in a Undefined behavior.
Array's created at global scope or with a static qualifier will be initialized to 0 or you can use initialization provided built in by the language or you can explicitly set each element to 0.
There are multiple ways of doing so, the best one depends on what behavior you want to extract from the array.

How to get dimensions of a multidimensional vector in C++

all
I am using multidimensional STL vector to store my data in C++. What I have is a 3D vector
vector<vector<vector<double>>> vec;
What I want to retrieve from it is :
&vec[][1][]; // I need a pointer that points to a 2D matrix located at column 1 in vec
Anyone has any idea to do so? I would be extremly appreciate any help!
Regards
Long
It is best to consider vec just as a vector whose elements happen to be
vectors-of-vectors-of-double, rather than as a multi-dimensional structure.
You probably know, but just in case you don't I'll mention it,
that this datatype does not necessarily represent a rectangular cuboid.
vec will only have that "shape" if you ensure that all the vectors are
the same size at each level. The datatype is quite happy for the vector vec[j]
to be a different size from the one at vec[k] and likewise for vec[j][n]
to be a vector of different size from vec[j][m], so that your structure is "jagged".
So you want to get a pointer to the vector<vector<double>> that is at
index 1 in vec. You can do that by:
vector<vector<double>> * pmatrix = &vec[1];
However this pointer will be an unnecessarily awkward means of accessing that
vector<vector<double>>. You certainly won't be able to write the
like of:
double d = pmatrix[j][k];
and expect to get a double at coordinates (j,k) in the "matrix addressed
by a pmatrix". Because pmatrix is a pointer-to-a-vector-of-vector-of-double;
so what pmatrix[j] refers to is the vector-of-vector-of-double (not vector-of-double)
at index j from pmatrix, where the index goes in steps of
sizeof(vector<vector<double>>). The statement will reference who-knows-what
memory and very likely crash your program.
Instead, you must write the like of:
double d = (*pmatrix)[j][k];
where (*pmatrix) gives you the vector-of-vector-of-double addressed by pmatrix,
or equivalently but more confusingly:
double d = pmatrix[0][j][k];
Much simpler - and therefore, the natural C++ way - is to take a reference,
rather than pointer, to the vector<vector<double>> at index 1 in vec. You
do that simply by:
vector<vector<double>> & matrix = vec[1];
Now matrix is simply another name for the vector<vector<double>> at index 1 in vec,
and you can handle it matrix-wise just as you'd expect (always assuming
you have made sure it is a matrix, and not a jagged array).
Another thing to consider was raised in a comment by manu343726. Do you
want the code that receives this reference to vec[1] to be able to
use it to modify the contents of vec[1] - which would include changing its
size or the size of any of the vector<double>s within it?
If you allow modification, that's fine. If you don't then you want to get
a const reference. You can do that by:
vector<vector<double> > const & matrix = vec[1];
Possibly, you want the receiving code to be able to modify the doubles
but not the sizes of the vectors that contain them? In that case, std::vector
is the wrong container type for your application. If that's your position I
can update this answer to offer alternative containers.
Consider using matrix from some linear algebra library. There are some directions here

Implementing own quicksort on dynamic array

I have to implement my own sort on a dynamic string array, e.g. of such array is:
string * sortArray;
I then read in the size of the array from a text file and make the array as long as needed and fill it. So, I have...
sortArray = new string[_numberOfNames];
for(int i = 0; i < _numberOfNames; ++i){
sin >> _data[i];
}
Now I need to create my own sorting method and I thought I'd go with quicksort. My problem is, I'm not sure how to go about it.
When I choose a pivot, how can I then go about setting up two more dynamic string arrays to put the lower values and highers values in to, then recurse on? There is no way of knowing before hand how big each array needs to be before I start putting values into them.
I thought I could do something like define the size of each array as being the same as the array being sorted, and then some how remove any unwanted empty spaces from the end, but I'm not sure this is possible?
Any help would be much appreciated.
P.S. I know about the std::sort, I already have this in the program, I'm just trying to implement a sort myself.
Two options as from the comments above:
1.) Use std::vector. There you can have variable size arrays.
2.) Use an "in place" version of quicksort that does the sorting in your original array. See http://en.wikipedia.org/wiki/Quicksort#In-place_version
Lets say you have array size N
and you pivot value is x
what you should do is like that, have two pointers one to the beginning(0) and one to the end (N-1). they should both move to the middle. when ever the beginning pointer value is greater than x and the end pointer value is lower than x switch their values. after you finished and placed x in his new location (where the two pointers met) continue recursionally for the part left to x and right to x.