Sorting 2D Dynamic Array C++ - c++

I am trying to sort a two dimensional dynamic array when row 1 is for product ID and row 2 is for the product price. I want to sort by product ID, and have the results displayed formatted with width of 5. Here is my code:
This section is fine and does what I am looking for:
void readData (int**, int, int);
void printData(int**, int, int);
void sortbyPartID(int**, int, int);
int main()
{
int index;
int **PriceSheet, rows, columns;
cout << "Enter the number of Products, and then the number of values associated with the products: ";
cout << "For default values, enter 5 (FIVE ITEMS, and enter 2 (TWO Values: ID and PRICE). ";
cin >> columns >> rows;
cout << endl;
PriceSheet = new int* [rows];
for (int row = 0; row < rows; row++)
PriceSheet [row] = new int[columns];
readData (PriceSheet, rows, columns);
cout << endl;
printData(PriceSheet, rows, columns);
sortbyPartID(PriceSheet, rows, columns);
return 0;
}
void readData (int **p, int rowSize, int colSize)
{
for (int row = 0; row < rowSize; row++)
{
cout << "Row ZERO is the Product ID and Row 1 is the Product Price\n";
cout << "Enter " << colSize << " numbers for the row number " << row << ": ";
for (int col = 0; col < colSize; col++)
cin >> p[row][col];
cout << endl;
}
}
void printData (int **p, int rowSize, int colSize)
{
cout << "\n\nThese are the Products IDs and Prices as entered in the system:\n";
for (int row = 0; row < rowSize; row++)
{
for (int col = 0; col < colSize; col++)
cout << setw(5) << p[row][col];
cout << endl;
}
}
THIS SECTION IS WHERE I NEED HELP
It reads correctly and prints the unsorted array also correctly, but I cannot figure out a way to sort the array. Specifically speaking, I need help on the void sortbyPartID function. I would like to use bubble sort, and I cannot figure out how to get this function to work. Any help with the sorting function/algorithm would be greatly appreciated.
void sortbyPartID (int **p, int rowSize, int colSize)
{
int swap = -1;
int end = colSize;
int sortedID = **p;
cout << "\n\nThese are the Products sorted Products IDs:\n";
for (int counter = colSize -1; counter >= 0; counter --)
for (int index = 0; index < end ; index ++)
{
if (sortedID[index] > sortedID[index + 1])
{
swap = *sortedID[index + 1];
sortedID[index + 1] = sortedID[index];
*sortedID[index] = swap;
}
}
for(int index = 0; index < end; index++)
{
cout << sortedID[index] << ", ";
}
cout << endl;
end --;
}
When I run, I get some weird results on the last section. Maybe I am missing something simple, not sure.

We can also perform this using do-while as follows:
bool isSwaped;
do
{
isSwaped = false;
for (int index = 0; index < end - 1 ; ++index)
{
if (p[index][0] > p[index + 1][0])
{
int swap = p[index + 1][0];
p[index + 1][0] = p[index][0];
p[index][0] = swap;
isSwaped = true;
}
}
} while (isSwaped);

You can simplify the entire thing by using objects. Objects allow you to handle the related data in a sane fashion. Also highly recommend are vectors instead of C arrays.
struct Product {
int id;
int price;
vector<int> others;
}
You can then store your products in vector<Product> my_products; and then sorting everything with
std::sort(my_products.begin(), my_products.end(),
[](const Product& a, const Product& b) { return a.id < b.id; });
You can keep the existing input/output format, but place the values in the right place. This way it's almost impossible to mess up the attributes and everything is easy to work with.

int sortedID = **p; is not what you want, and should be removed. (I think you wanted int** sortedID = p;)
Your bubble-sort should be something like:
for (int counter = colSize -1; counter >= 0; --counter)
{
for (int index = 0; index < end - 1 ; ++index)
{
if (p[index][0] > p[index + 1][0])
{
// std::swap(p[index], p[index + 1]);
int* swap = p[index + 1];
p[index + 1] = p[index];
p[index] = swap;
}
}
}
Live Demo

Related

Why the array is not sorted correctly?

the problem is
arange the columns of the array X (n, m) in ascending order.
I wrote such code in c ++ myself, but in the end it does not sort all the columns correctly. Please help if anyone knows.
#include <iostream>
using namespace std;
int main() {
int n, m;
cout << "array size: n = ";
cin >> n;
cout << "array size: m = ";
cin >> m;
int array[n][m];
int arrayS[n];
for (int z = 0; z < n; z++) {
for (int a = 0; a < m; a++) {
cin >> array[z][a];
}
}
for (int i = 0; i < n; i++) {
arrayS[i] = array[i][0];
}
for (int y = 0; y < n; y++) {
for (int i = 0; i < m; i++) {
cout << array[y][i] << " ";
}
cout << endl; //endline
}
cout << "************************************\n";
cout << "massivin sutunlari\n";
int enk = 0;
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
if (arrayS[j] > arrayS[j + 1])
{
enk = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = enk;
}
}
for (int i = 0; i < n; i++)
{
cout << arrayS[i] << " ";
}
}
First of all, we need to make your code compilable. You are using so called VLA (variable length arrays), like in int array[n][m];. Rhese VLAs are not part of the C++ language and will not compile. I replaced them with a std::vector which will work in the same way. Then I corrected the code identations (I edited also your question) and then it is possible to compile.
It will then lool like the below (but of course still not working)
#include <iostream>
#include <vector>
int main() {
int n, m;
std::cout << "array size: n = ";
std::cin >> n;
std::cout << "array size: m = ";
std::cin >> m;
std::vector<std::vector<int>> array(n, std::vector<int>(m, 0));
std::vector<int> arrayS(n);
for (int z = 0; z < n; z++) {
for (int a = 0; a < m; a++) {
std::cin >> array[z][a];
}
}
for (int i = 0; i < n; i++) {
arrayS[i] = array[i][0];
}
for (int y = 0; y < n; y++) {
for (int i = 0; i < m; i++) {
std::cout << array[y][i] << " ";
}
std::cout << std::endl; //endline
}
std::cout << "************************************\n";
std::cout << "massivin sutunlari\n";
int enk = 0;
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
if (arrayS[j] > arrayS[j + 1])
{
enk = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = enk;
}
}
for (int i = 0; i < n; i++)
{
std::cout << arrayS[i] << " ";
}
}
Some basic hints. Please use "speaking" variable names and write many many comments, best, one than more comment per line of code. Then you would already see the problems by yourself.
You have some hard bugs in your code that will most likely crash you program. Where you thy to sort, you use the magic number 9 (for whatever reasons) and so go out of bounds of the define arrays.
Additionally, your implementation of bubble sort is wrong. You may check many many examples in the net.
Then, you do only sort one column. You need to implement a bubble sort for each column of your matrix.
As a next step I will use better variable names and write comments. The code will still not work. But see and understand the difference.
#include <iostream>
#include <vector>
int main() {
// Here we will define the dimensions for our matrix
int numberOfRows{}, numberOfColumns{};
// Inform user what to do. Enter number of rows of the matrix
std::cout << "\nPlease enter the number of rows: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfRows;
// Inform user what to do. Enter number of columns of the matrix
std::cout << "\nPlease enter the number of columns: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfColumns;
// Define the array for the complete 2d matrix
std::vector<std::vector<int>> array(numberOfRows, std::vector<int>(numberOfColumns, 0));
// We can store one column here
std::vector<int> arrayS(numberOfRows);
// Inform user what to do. Enter all data for the matrix
std::cout << "\nPlease enter all data for the matrix";
// Now read all data, for all rows and columns from the user, via std::cin
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cin >> array[row][col];
}
}
// Copy the first column in a separate array
for (int i = 0; i < numberOfRows; i++) {
arrayS[i] = array[i][0];
}
// Show current data in our matrix
std::cout << "\n\nThe matrix:\n\n";
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
// SHow some status message
std::cout << "\n\n\n************************************\n";
std::cout << "Sorted first column\n";
// This is a temporary variable needed to swap 2 values
int tempValue = 0;
// Try to do bubble sort
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
if (arrayS[j] > arrayS[j + 1])
{
tempValue = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = tempValue;
}
}
// Show the result of the sorting
for (int i = 0; i < numberOfRows; i++)
{
std::cout << arrayS[i] << " ";
}
}
Next, we fix the sorting for one column.
Only minor changes needed:
#include <iostream>
#include <vector>
int main() {
// Here we will define the dimensions for our matrix
int numberOfRows{}, numberOfColumns{};
// Inform user what to do. Enter number of rows of the matrix
std::cout << "\nPlease enter the number of rows: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfRows;
// Inform user what to do. Enter number of columns of the matrix
std::cout << "\nPlease enter the number of columns: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfColumns;
// Define the array for the complete 2d matrix
std::vector<std::vector<int>> array(numberOfRows, std::vector<int>(numberOfColumns, 0));
// We can store one column here
std::vector<int> arrayS(numberOfRows);
// Inform user what to do. Enter all data for the matrix
std::cout << "\nPlease enter all data for the matrix\n";
// Now read all data, for all rows and columns from the user, via std::cin
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cin >> array[row][col];
}
}
// Copy the first column in a separate array
for (int i = 0; i < numberOfRows; i++) {
arrayS[i] = array[i][0];
}
// Show current data in our matrix
std::cout << "\n\nThe matrix:\n\n";
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
// SHow some status message
std::cout << "\n\n\n************************************\n";
std::cout << "Sorted first column\n";
// This is a temporary variable needed to swap 2 values
int tempValue = 0;
// Try to do bubble sort
// Go over all entries-1 in the column array.
// And compare the current value with the next value
for (int i = 0; i < numberOfRows-1; i++)
for (int j = 0; j < numberOfRows - 1; j++)
{
// If this value is bigger than the following value, then swap them
if (arrayS[j] > arrayS[j + 1])
{
// Swap
tempValue = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = tempValue;
}
}
// Show the result of the sorting
for (int i = 0; i < numberOfRows; i++)
{
std::cout << arrayS[i] << " ";
}
}
This works already. But, my gues is that all columns shall be sorted.
Then, finally, it would look like that:
#include <iostream>
#include <vector>
int main() {
// Here we will define the dimensions for our matrix
int numberOfRows{}, numberOfColumns{};
// Inform user what to do. Enter number of rows of the matrix
std::cout << "\nPlease enter the number of rows: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfRows;
// Inform user what to do. Enter number of columns of the matrix
std::cout << "\nPlease enter the number of columns: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfColumns;
// Define the array for the complete 2d matrix
std::vector<std::vector<int>> array(numberOfRows, std::vector<int>(numberOfColumns, 0));
// Inform user what to do. Enter all data for the matrix
std::cout << "\nPlease enter all data for the matrix\n";
// Now read all data, for all rows and columns from the user, via std::cin
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cin >> array[row][col];
}
}
// Show current data in our matrix
std::cout << "\n\nThe matrix:\n\n";
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
// SHow some status message
std::cout << "\n\n\n************************************\n";
std::cout << "Matrix with sorted column\n";
// This is a temporary variable needed to swap 2 values
int tempValue = 0;
// Try to do bubble sort
// Go over all entries-1 in the column array.
// And compare the current value with the next value
// Do for all columns
for (int col = 0; col < numberOfColumns; ++col)
for (int i = 0; i < numberOfRows-1; ++i)
for (int row = 0; row < numberOfRows - 1; ++row)
{
// If this value is bigger than the following value, then swap them
if (array[row][col] > array[row + 1][col])
{
// Swap
tempValue = array[row][col];
array[row][col] = array[row + 1][col];
array[row + 1][col] = tempValue;
}
}
// Show the result of the sorting
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
}

My N Queen Problem works up until n = 5 and I don't know why C++

I'm still fairly new to coding so take it easy but I'm working on the N Queen problem which calls for the amount of solutions for a board of n size where you can place a queen on every row. My code works up to n=4 and then n=5 outputs 11 and all n's after output 0. -1s appear in placements[] up to n=5 and then they aren't input into the array afterwards. I'm pretty clueless now so some help would be appreciated.
#include <iostream>
using namespace std;
//MAXROWS is same as MAXCOLUMNS or BOARDSIZE
const int MAXROWS = 20;
//queens' placements in each row
int placements[MAXROWS];
int n = 0;
int solutionsCount = 0;
bool canPlaceQueen(int row, int column)
{
for(int j = 0; j < row; j++)
if((placements[j] == column) // is there a queen in same column?
|| (abs(placements[j] - column) == abs(j-row))) // checks diagonals
return false; // column difference is same as row difference?
return true;
}
bool correctSolution()
{
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
if (placements[i] == placements[j])
{
return false;
}
}
for (int k = 0; k < n; k++)
{
if (placements[k] == -1)
{
return false;
}
}
return true;
}
void placeQueens(int row) {
//try to place queen in each column in current row
//then continue to explore: placeQueens(row+1)
//for each successful queen placement in final row, increment solutionsCount!
for (int i = 0; i < n; i++)
{
if (canPlaceQueen(row, i))
{
placements[row] = i;
if (row < n-1)
{
placeQueens(row+1);
}
}
else
{
placements[row] = -1;
}
if (correctSolution())
{
solutionsCount++;
cout << "add" << placements[0] << placements [1] << placements[2] << placements[3] << endl;
}
}
cout << "new" << placements[0] << placements [1] << placements[2] << placements[3] << endl;
for (int j = 0; j < n; j++)
{
placements[j] = 0;
}
}
int main() {
cout << "Enter the board size: ";
cin >> n;
placeQueens(0);
cout << "Number of solutions: " << solutionsCount << endl;
}
Hope this helps you and your endeavors, sport!
#include <iostream>
using namespace std;
//MAXROWS is same as MAXCOLUMNS or BOARDSIZE
const int MAXROWS = 20;
//queens' placements in each row
int placements[MAXROWS];
int n = 0;
int solutionsCount = 0;
bool canPlaceQueen(int row, int column)
{
for (int j = 0; j < row; j++)
if ((placements[j] == column) // is there a queen in same column?
|| (abs(placements[j] - column) == abs(j - row))) // checks diagonals
return false; // column difference is same as row difference?
return true;
}
void placeQueens(int row)
{
//try to place queen in each column in current row
//then continue to explore: placeQueens(row+1)
//for each successful queen placement in final row, increment solutionsCount!
if (row == n) //If the last row has been reached then there is a solution
{
solutionsCount++; //incrementing the solution count
return; //returning back
}
for (int column = 1; column <= n; column++) // To check all the columns from 1 to n
{
if (canPlaceQueen(row, column) == true)
{
placements[row] = column; //placing the queen in Row row on Column column
placeQueens(row + 1); //calling the next row
placements[row] = 0; //removing the queen from this column
}
}
}
int main()
{
cout << "Enter the board size: ";
cin >> n;
placeQueens(0);
cout << "Number of solutions: " << solutionsCount << endl;
}
Sincerely,
Mike

Sort elements of secondary diagonal in ascending order C++

As I think, I need to transform function printSecondaryDiagonal (that actually print elements of secondary diagonal) into one-dimensional array and then sort its elements in ascending order, right?
P.S. Two-dimensional array in the beginning must be necessarily a dynamic one. Also, cannot do it using vector. Only malloc, calloc and new
#include <iostream>
#include <iomanip>
using namespace std;
void getManual(int** arr, int rows, int columns);
void getRandom(int** arr, int rows, int columns);
void printSecondaryDiagonal(int** arr, int rows, int columns);
void main() {
int rowCount = 5;
int colCount = 6;
cout << "Enter quantity of rows: ";
cin >> rowCount;
cout << "Enter quantity of columns: ";
cin >> colCount;
int** arr = new int* [rowCount];
for (int i = 0; i < rowCount; i++) {
arr[i] = new int[colCount];
}
cout << " Array formation algorithm\n";
start:
cout << "Input number : \n1 for manual\n2 for random\n";
int k;
cin >> k;
switch (k) {
case 1: getManual(arr, rowCount, colCount);
break;
case 2: getRandom(arr, rowCount, colCount);
break;
default:cout << "Input 1 or 2, please.";
cout << endl << endl;
goto start;
}
cout << endl;
printSecondaryDiagonal(arr, rowCount, colCount);
for (int i = 0; i < rowCount; i++) { //очищуємо память для кожного рядка
delete[] arr[i];
}
delete[] arr;
}
void getManual(int** arr, int rows, int columns) { //введення з клавіатури
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
cout << "a[" << i << "][" << j << "]=";
cin >> arr[i][j];
//cin >> *(*(arr + i) + j); //вказівникова форма
}
}
}
void getRandom(int** arr, int rows, int columns) { //випадкова генерація чисел
int lowest = -21, highest = 34;
int i, j;
srand(time(NULL));
// ініціалізація масива
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
arr[i][j] = lowest + rand() % (highest - lowest + 1);
cout << setw(7) << arr[i][j];
}
cout << endl;
}
}
Function that I need to transform into one-dimensional array and which is the main problem for me:
void printSecondaryDiagonal(int** arr, int rows, int columns) {
cout << "Secondary Diagonal: ";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
// Condition for secondary diagonal
if ((i + j) == (columns - 1)) {
cout << arr[i][j] << setw(7);
}
}
}
}
The elements of the secondary diagonal can be extract with one for loop as I will show. The secondary diagonal will be save in an 1-d array `secDiag[i]`. Then, using `std::sort` in `algorithm` head file to sort this array in ascending order.
void printSecondaryDiagonal(int** arr, int rows, int columns) {
cout << "Secondary Diagonal: ";
int *secDiag = new int [rows];
int r, c;
for (r = 0; r < rows ; r++) {
c = columns - r -1;
if (c < 0) break;
secDiag[r] = arr[r][c];
}
for (int i =0; i<r; i++) std::cout << setw(7) << secDiag[i];
std::cout << std::endl;
std::cout << "After sorted: ";
std::sort(secDiag, secDiag+r);
for (int i =0; i<r; i++) std::cout << setw(7) << secDiag[i];
std::cout << std::endl;
delete [] secDiag;
}
A test run:
Enter quantity of rows: 3
Enter quantity of columns: 3
Array formation algorithm
Input number :
1 for manual
2 for random
2
33 -13 29
-7 -2 10
-8 18 6
Secondary Diagonal: 29 -2 -8
After sorted: -8 -2 29
void printSecondaryDiagonal(int** arr, int rows, int columns) {
cout << "Secondary Diagonal: ";
int i = 0;
int j = columns - 1;
int k = 0;
int size =0;
if (rows>columns)
{
size = columns;
}
else
{
size = rows;
}
int *diagonal = new int[size];
while (i < rows && j >= 0)
{
diagonal[k] = arr[i][j];
cout << arr[i][j] << setw (7);
i++;
j--;
k++;
}
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; j < size - i - 1; j++)
{
if (diagonal[j] > diagonal[j + 1])
{
// swap arr[j+1] and arr[j]
int temp = diagonal[j];
diagonal[j] = diagonal[j + 1];
diagonal[j + 1] = temp;
}
}
}
for (int r = 0; r < size; r++)
{
cout << diagonal[r] << endl;
}
delete [] diagonal;
}

Having trouble applying sorting to this program

The goal of the program is to generate a multidimensional array, of variable size, the number of columns being the numbers of political parties, the number of rows being the "round" we're in, and the entries of the first row being the number of votes each political party got, then as you get into the second row, round 2, you divide all the values in the first row by 2, in round 3 you divide the values in the first row by 3, and the same thing goes for how many rows the thing has.
I got all that done, but after those operations are over, I want to be able to find the N largest elements, n being the number of rows, and place those elements in a vector, for some reason I can't seem to find, when I run it nothing is displayed on the console, when I get to the part where I want it to sort out the elements, it blacks out, and then crashes.
I've tried changing things around, I don't really think the problem is in the algorithm itself, as I've tried it with static arrays that I've filled randomly, and it sorted those out just fine. Like I said I don't really know where the problem is so I'll show a large part, I've cut out everything not pertinent.
double** ELEITORAL;
void bubble_sort(double** ELEITORAL)
{
int x, y;
double tItem;
int PassCount;
bool Mudou;
for (PassCount = 0; PassCount < (MAX_rows * MAX_columns); PassCount++)
{
//orders the rows
for (y = 0; y < MAX_columns; y++)
{
Mudou = true;
while (Mudou)
{
Mudou = false;
for (x = 1; x < MAX_rows; x++)
{
if (ELEITORAL[x - 1][y] > ELEITORAL[x][y])
{
Mudou = true;
tItem = ELEITORAL[x - 1][y];
ELEITORAL[x - 1][y] = ELEITORAL[x][y];
ELEITORAL[x][y] = tItem;
}
}
}
}
//ORDERS THE COLUMNS
for (x = 0; x < MAX_rows; x++)
{
Mudou = true;
while (Mudou)
{
Mudou = false;
for (y = 1; y < MAX_columns; y++)
{
if (ELEITORAL[x][y - 1] > ELEITORAL[x][y])
{
Mudou = true;
tItem = ELEITORAL[x][y - 1];
ELEITORAL[x][y - 1] = ELEITORAL[x][y];
ELEITORAL[x][y] = tItem;
cout << "entrei";
system("pause");
}
}
}
}
}
}
void DisplayTheArray(double** ELEITORAL)
{
for (int y = 0; y < MAX_columns; y++)
{
for (int x = 0; x < MAX_rows; x++)
{
cout.width(5);
cout << ELEITORAL[x][y];
}
cout << endl;
}
cout << endl;
}
void fill(double **p, int rowsize, int colsize) {
std::cout << std::fixed;
std::cout << std::setprecision(1);
printf("\n Introduza o n%cmero de votos nas listas por ordem \n", 163);
for (int col = 0; col < colsize; col++)
{
cin >> p[row][col];
}
cout << endl;
for (int row = 1; row < rowsize; row++)
{
for (int col = 0; col < colsize; col++)
{
p[row][col] = (p[0][col]/(row + 1));
}
cout << endl; //preenche as linhas
}
}//FILL OUT THE ARRAY
void print(double **p, int rowsize, int colsize)
{
for (int i = 0; i < header.size(); i++) { //HEADER IS TO STORE THE
//NAMES OF THE POLITICAL PARTIES
cout << setw(9) << header[i] << " ";
}
cout << endl;
for (row = 0; row < rowsize; row++) //IMPRIME A MATRIZ EM SI
{
for (col = 0; col < colsize; col++)
{
cout << setw(10) << p[row][col];
}
cout << endl;
}
}//PRINTS THE ARRAY
int MATRIZ()
{
std::cout << std::fixed;
std::cout << std::setprecision(1);
double rows, columns;
printf("\n Qual o n%cmero de candidatos a eleger? \n", 163);
cin >> rows;
printf("\n Qual o n%cmero de listas candidatas? \n", 163);
cin >> columns;
for (i = 0; i < columns; i++)
{
cout << " Qual o nome da lista " << i+1;
cout << endl;
cin >> nomL;
header.push_back(nomL);
}
cout << endl;
system("cls");
ELEITORAL = new double*[rows];
for (int row = 0; row < rows; row++)
{
ELEITORAL[row] = new double[columns];
}
fill(ELEITORAL, rows, columns);
cout << endl;
//After this I have a switch, in case 5 I call the functions
//giving me trouble
case '5':
{
bubble_sort(ELEITORAL);
DisplayTheArray(ELEITORAL);
break;
}
Your display function is sketchy as you assume that the array has MAX dimensions. So my bet would be that your program seg faults due to memory access violation. Please, don't use new, instead use a vector. You won't have to pass the length as a separate parameter and in this case you won't get it wrong. Also double is not appropriate type for indexing, turn on compiler warnings and fix them.
Here's a simple example how can vector be used to make a matrix:
#include <iostream>
#include <vector>
using row_t = std::vector<double>;
using matrix_t = std::vector<row_t>;
//matrix_t = std::vector<std::vector<double>>; Vector of vectors of double
//Pass by reference to avoid copy
//Pass by const if the matrix should be read-only
void printMatrix(const matrix_t& mat)
{
for(auto& row: mat)
for(auto& val: row)
std::cout<<val << ' ';
std::cout<<'\n';//Use this instead of endl if you want just a new line
}
void doubleMatrix(matrix_t& mat)
{
//If you need access to indices during iterating
for(std::size_t r = 0; r < mat.size();++r)
for(std::size_t c = 0; c < mat[r].size();++r)
mat[r][c] *=2.0;
}
int main()
{
std::size_t rows, columns;
std::cin >> rows;
std::cin >> columns;
double fill_value = 0.0;
matrix_t matrix(rows);
//Resize rows to given column width.
for(auto& row: matrix)
row.resize(columns, fill_value);
printMatrix(matrix);
doubleMatrix(matrix);
printMatrix(matrix);
}
Last thing I noticed, If you want to swap two values, use std::swap.

Replacing values in a 2D array

I have to create a program that allows a user to fill in a (partial) Latin Square of order 4. You can use 0's to represent empty cells. The user will give the number to place, the row and column. The number should only be placed if it does not violate the properties of a partial Latin square and it shouldn't rewrite numbers that have already been placed.
I have an matrix that is outputting all zeroes now. So next I have to replace each of these values by what the user is inputting. The problem is I don't know how to do this.
Here is my code:
#include <iostream>
using namespace std;
const int ORDER = 4;
void fill (int m[], int order);
void outputMatrix (int m[], int order);
void replaceValue (int m[], int order, int n, int row, int column);
int main(){
int matrix[ORDER];
int row;
int column;
int n;
fill (matrix, ORDER);
outputMatrix (matrix, ORDER);
do {
cout << "Enter the number to place, the row and the column, each seperated by a space: ";
cin >> n;
cin >> row;
cin >> column;
}while (n > 0 || n <= ORDER);
if (n <= 0 || n >= ORDER){
cout << "Thank you";
cout << endl;
}
return 0;
}
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
void outputMatrix (int m[], int order){
int c = 0;
for (int i = 0; i < order*order; i++){
c++;
cout << m[i] << ' ';
if (c == order){
cout << endl;
c = 0;
}
}
cout << endl;
}
void replaceValue (int m[], int order, int n, int row, int column){
for (int i = 0; i < order; i++){
m[order] = m[row][column];
m[row][column] = n;
}
}
How do I replace values in a Matrix in C++?
If you have a matrix, matrix[row][col] = value; would do the trick. However, I see that you allocate a single array. Make sure you look at this.
EDIT:
I looked closer at you code and you are doing some things wrong.
First:
matrix[ORDER]
will create a single array of ORDER values. If you want and ORDER by ORDER matrix try:
matrix[ORDER][ORDER]
Second:
You are calling:
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
with an of size 4 and order == 4. This will loop outside the array and give you problems.
Try something like:
matrix[ORDER][ORDER];
for (int row = 0; row != ORDER; ++row)
{
for (int col = 0; col != ORDER; ++col)
{
matrix[row][col] = 0;
}
}
Hope this helps.
You can't really write arr[i][j] if arr is defined as arr[]. There's no information about the length of the row (how many columns there are).
You could use arrays of type arr[][4], and write your functions like so:
// The & is to pass by reference.
void print(int (&arr)[][4], int length)
{
for(int i = 0; i < length; i++) {
for(int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
But in my opinion for a low-order multidimensional array like this one, using a typedef for a vector of vectors is the better option:
typedef vector<vector<int> > Matrix;
void print(Matrix& arr)
{
for(int i = 0; i < arr.size(); i++) {
for(int j = 0; j < arr[i].size(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
In either case, writing arr[i][j] = k will behave as you expect.
The easiest way to clear/zero your matrix is that:
memset( &matrix, 0, sizeof(matrix));
;-)