Copying values of 2D array into another - c++

I have a 2D array that I want to assign the values of another array. I'm making a game of life simulator and have everything else working but this. My code is this:
for(int i = 0; i < ROWS; i++) {
for (int j = 0; i < COLS; j++) {
current[i][j] = next[i][j];
}
}
current and next are both bool's. I keep getting the error code EXC_BAD_ACCESS in X-Code. I'm unsure what I'm doing wrong

To re-iterate my comment, the innerloop compares i with COL rather than j. So
for(int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
current[i][j] = next[i][j];
}
}
should solve the issue

Related

Iterate over vectors with n and n*n elements

I have this Google test assertions
ASSERT_FLOAT_EQ(longerVector[0], shorterVector[0]);
ASSERT_FLOAT_EQ(longerVector[1], shorterVector[1]);
ASSERT_FLOAT_EQ(longerVector[2], shorterVector[2]);
ASSERT_FLOAT_EQ(longerVector[3], shorterVector[0]);
ASSERT_FLOAT_EQ(longerVector[4], shorterVector[1]);
ASSERT_FLOAT_EQ(longerVector[5], shorterVector[2]);
ASSERT_FLOAT_EQ(longerVector[6], shorterVector[0]);
ASSERT_FLOAT_EQ(longerVector[7], shorterVector[1]);
ASSERT_FLOAT_EQ(longerVector[8], shorterVector[2]);
as you can see, there are two vectors, shorter with n elements and longer with n*n elements (in this case 3 and 9 respectively).
How could I create two nested for loops, which would make my code shorter and simpler?
I tried for example this but it failed. I understand why but I was not able to come up with anything better.
for(size_t i = 0; i < shorterVector.size(); i++)
{
for(size_t j = 0; j < shorterVector.size(); j++)
{
ASSERT_FLOAT_EQ(longerVector(i*j), shorterVector(j);
}
}
Thank you very much for any help and I apologize for maybe a dumb question.
Use this instead
for(size_t i = 0; i < longerVector.size(); i++)
{
ASSERT_FLOAT_EQ(longerVector[i], shorterVector[i%3]);
}
for(size_t i = 0; i < shorterVector.size(); i++)
{
for(size_t j = 0; j < shorterVector.size(); j++)
{
ASSERT_FLOAT_EQ(longerVector[i*shorterVector.size() + j], shorterVector[j]);
}
}
You should assert before that shorterVector.size() * shorterVector.size() == longerVector.size().
If you do not want to have the multiplication in the inner loop body you can do:
for(size_t i = 0, k = 0; i < shorterVector.size(); i++)
{
for(size_t j = 0; j < shorterVector.size(); j++)
{
ASSERT_FLOAT_EQ(longerVector[k++], shorterVector[j]);
}
}

How to initialize a character or string array using for loop in c++?

I want to make a 2 dimensional array of 13 rows and 6 columns all initialized with character X. to do so I'm doing this.
char myseats[13][5];
for (int i; i < 13; i++)
{
myseats[i] = { 'X' };
for (int j; j < 5; j++)
{
myseats[j] = {'X'};
}
}
}
however this gives me a error and the array wont initialize with X, same is the case with string. How can I achieve my purpose can anyone please help me?
If you want to access fields of two dimensional array, you should use myseats[i][j] (first you specify row, then the column). Also, your for loops are written incorrectly. When you initialize any variable in the body of for loop, you should assign its value (otherwise i and j can have any value that can be saved in int). Your code should look like that:
char myseats[13][5];
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 5; j++)
{
myseats[i][j] = {'X'};
}
}
Try this:
char myseats[13][5];
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 5; j++)
{
myseats[i][j] = 'X';
}
}
First, the i and j where not initialized in the loop. You need to define at what index you want them to start.
Second, the correct way to access a two dimensional array is with the syntax array[row_index][column_index] = 'your_desired_value_here'.

Heap Corruption Detected in C++

I keep getting the error Heap Corruption Detected. I have read through several questions on here, but I can't quite find out what is causing this in my code. I am trying to create a 2d array that will hold a matrix that is read from a text file.
// Create a 2d matrix to hold the matrix (i = rows, j = columns)
matrix = new int*[cols];
for(int i = 0; i <= cols; i++) {
matrix[i] = new int[rows];
}
// Populate the matrix from the text file
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
inputFile >> matrix[i][j];
}
}
My destructor is:
for(int i = 0; i <= cols; i++) {
delete[] matrix[i];
}
delete[] matrix;
I've tried debugging, but that does do much help in this case. Any suggestions?
matrix = new int*[cols];
for(int i = 0; i <= cols; i++) {
matrix[i] = new int[rows];
}
For an array with cols elements, the index is from 0 to cols - 1 inclusively.
The heap corruption will be detected when
delete [] matrix;
Since matrix[cols] write a position out of array bound.
UPDATE
As #DanielKO (thank you buddy :p) pointed out in the comment
there is a mismatch, the "Populate the matrix..." loop makes "i"
iterate over "rows" when it should be iterating over "cols".
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
inputFile >> matrix[i][j];
When you allocated you went from 0 to cols in i. Now you're changing i to be rows.
EDIT: Below would honor your commented row/column rules and follow RAII:
std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));
for( int i=0; i<rows; ++i ) {
for( int j=0; j<cols; ++j ) {
inputFile >> matrix[i][j];
}
}
// no need for delete matrix cleaned up when leaving scope.

How to put NULL in all cells of a matrix vector?

i'm trying to initialize all cells of a matrix with NULL values, but something is wrong here.
the code :
vector<vector<Distance*> > distanceMatrix;
for (int i = 0; i < 7 ; i++)
for (int j = 0; j < 7 ; j++)
distanceMatrix[i][j].push_back(NULL);
i bet it's something stupid, thanks for the help.
From the std::vector reference page:
Vectors can be constructed with some values in them.
You may try:
vector<vector<Distance*> > distanceMatrix(7, vector<Distance*>(7, NULL));
Also, regarding your problem:
vector<vector<Distance*> > distanceMatrix;
for (int i = 0; i < 7 ; i++)
for (int j = 0; j < 7 ; j++)
distanceMatrix[i][j].push_back(NULL); //1
When you code first reach //1, distanceMatrix[i] resolves to distanceMatrix[0] but you did not call distanceMatrix.push_back(vector<Distance*>()) so you are referring to a non initialized cell.
To correct code would have been:
vector<Distance*> vec;
for (int j = 0; j < 7 ; j++)
vec.push_back(NULL);
vector<vector<Distance*> > distanceMatrix;
for (int i = 0; i < 7 ; i++)
{
distanceMatrix.push_back(vec);
}
Which is still far worse than my first suggestion.
Since the matrix is empty to begin with, you need to push_back every value and every row, not depending on its position in the matrix:
vector<Distance*> row;
for(int j=0; j < 7; j++)
row.push_back(NULL);
vector<vector<Distance*> > distanceMatrix;
for(int i=0; i < 7; i++)
distanceMatrix.push_back(row);

optimize 2D array in C++

I'm dealing with a 2D array with the following characteristics:
const int cols = 500;
const int rows = 100;
int arr[rows][cols];
I access array arr in the following manner to do some work:
for(int k = 0; k < T; ++k) { // for each trainee
myscore[k] = 0;
for(int i = 0; i < cols; ++i) { // for each sample
for(int j = 0; j < rows; ++j) { // for each expert
myscore[k] += delta(i, anotherArray[k][i], arr[j][i]);
}
}
}
So I am worried about the array 'arr' and not the other one. I need to make this more cache-friendly and also boost the speed. I was thinking perhaps transposing the array but I wasn't sure how to do that. My implementation turns out to only work for square matrices. How would I make it work for non-square matrices?
Also, would mapping the 2D array into a 1D array boost the performance? If so, how would I do that? Finally, any other advice on how else I can optimize this... I've run out of ideas, but I know that arr[j][i] is the place where I need to make changes because I'm accessing columns by columns instead of rows by rows so that is not cache friendly at all.
Thanks,
Hristo
A general in-place matrix transposition is very difficult, but if you're okay with transposing it to another array, then it's pretty simple.
const int cols = 500;
const int rows = 100;
int arr[rows][cols];
// fill arr[][]
int arrT[cols][rows];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
arrT[c][r] = arr[r][c];
}
}
Of course, depending on how you're getting arr[][], you can just fill arrT[][] directly instead.
However, there may be a simpler solution of simple swapping the order of the loops.
for(int k = 0; k < T; ++k) { // for each trainee
myscore[k] = 0;
for(int j = 0; j < rows; ++j) { // for each expert
for(int i = 0; i < cols; ++i) { // for each sample
myscore[k] += delta(i, anotherArray[k][i], arr[j][i]);
}
}
}
Yes, 1d should be faster than 2d. C and C++ arrays are always 1d (internally).
When you call something like
array[row][col]
the compiler actually calculates
col + row * maxcols
and uses that as the actual index of a 1d array. You might as well do that yourself. Cycling through an entire array will be way faster, and random access will be equally fast as in a 2d array.
for(int i = 0; i < N; ++i) { // for each sample
for(int j = 0; j < E[i]; ++j) { // for each expert
... arr[j][i] ... // each ++j causes a large stride => poor caching
}
}
transpose the loops:
for(int j = 0; j < E[i]; ++j) { // for each expert
for(int i = 0; i < N; ++i) { // for each sample
... arr[j][i] ... // each ++i looks to the next word in memory => good
}
}
Of course, without seeing everything else in the program, I can't say if that would cause a problem. If delta doesn't have side effects, you should be fine.
You want memory accesses to be adjacent. In your case simply swap I and j when accessing arr.