Passing an array of chars to a function - c++

I have this code. I am trying to pass a character array to a function and I get an error saying:
"Expected primary expression before the ']' token " at line 21
on which I call the function:
#include <iostream>
#include <cstring>
using namespace std;
char* mostFrequentWord(int, char [][10]);
int main()
{
int br = 0, n, br1 = 0;
char str[100][10];
cin >> n;
for(int i=0; i<n; ++i)
{
cout << " cin >> str"<< i << "= ";
cin>> str[i];
}
cout << mostFrequentWord(n, str[][10]) <<endl;
int m;
for(int i=0; i<n-1; ++i)
{
for(int j=i+1; j<n; ++j)
{
if(!strcmp(str[i],str[j]))
{
++br;
}
}
if(br>br1)
{
br1 = br;
m = i;
}
}
cout << str[m] <<endl;
return 0;
}
char* mostFrequentWord(int n, char str[][10])
{
int m, br = 0, br1 = 0;
for(int i=0; i<n-1; ++i)
{
for(int j=i+1; j<n; ++j)
{
if(!strcmp(str[i],str[j]))
{
++br;
}
}
if(br>br1)
{
br1 = br;
m = i;
}
}
return str[m];
}

This line:
cout << mostFrequentWord(n, str[][10]) <<endl;
needs to read
cout << mostFrequentWord(n, str) <<endl;

You answer is in your question:. Just pass the str.
cout << mostFrequentWord(n, str) <<endl;

Try calling the function this way
mostFrequentWord(n,str)
This should work. Rest of the code is fine.

Related

MAX value of matrix and saving indexes in the same loop

I get a NxM sized matrix and I have to find the max value, the number of max values and the lines that contain it.
I tired using three for{for{}} loops, but it took too long. This method seems to work for small inputs, but when I try it with a 1000x1000 matrix, it finishes before it even takes all the input.
I realise this may be too much of a noob question, but I couldn't find anything else.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int n, m;
int crnt{-51}, cnt{0};
cin >> n >> m;
int vekt[m];
int lines[n];
int inp;
for(int i=0; i<n; i++)
{
for(int p=0; p<m; p++)
{
cin >> vekt[p];
}
for(int j=0; j<m; j++)
{
if(vekt[j] == crnt)
{
lines[cnt] = i + 1;
cnt += 1;
}
if(vekt[j] > crnt)
{
crnt = vekt[j];
lines[0] = i + 1;
cnt = 1;
}
}
}
cout << cnt;
for(int i=0; i<cnt; i++)
{
cout << " " << lines[i];
}
return 0;
}
EDIT : not using vector or [n] was just easier... I simply saved it to a variable and used a bool:
int main()
{
int n, m;
int crnt{-51}, cnt{0};
cin >> n >> m;
int vekt[m];
int lines[n];
int inp;
bool inLine;
inLine = false;
for(int i=0; i<n; i++)
{
inLine = false;
for(int j=0; j<m; j++)
{
cin >> inp;
if(inp == crnt && inLine == false)
{
lines[cnt] = i + 1;
cnt += 1;
inLine = true;
}
if(inp > crnt)
{
crnt = inp;
lines[0] = i + 1;
cnt = 1;
}
}
}
cout << cnt;
for(int i=0; i<cnt; i++)
{
cout << " " << lines[i];
}
return 0;
}
This cut the time by enough so that I went under the limit.
int vekt[m]; is not standard C++, it is a variable length array (which some compilers allow as extension). Use std::vector instead.
That would also fix the bug you currently have: If cnt >= n (i.e. if you find more maxima than the matrix has lines), you will go out of bounds of lines and your program will most likely crash (although anything could happen), which is more likely to happen with larger matrices.
You can do this instead:
Declaration and initialization:
std::vector<int> linesWithMaxima;
When you find another value equal to the current maximum:
linesWithMaxima.push_back(i+1);
When you find a new maximum (larger than current):
linesWithMaxima.clear();
linesWithMaxima.push_back(i+1);
Note that this will list a line with multiple (identical) maxima multiple times. If you want to avoid duplicates, you can either check that you have not already added the current line (linesWithMaxima.back() != i+1) or use std::sort, std::unique and std::vector::erase.
Other than that your code looks fine. I would recommend naming the loop indices better (line instead of i etc.) and possibly merging the p and j loop because separating them seems to have no purpose. And if you want the most negative integer, use std::numeric_limits<int>::lowest().
Check this realization, without STL and vectors:
void input_matrix(int **&matrix, int &lines, int &columns)
{
int m = 0, n = 0;
cout << "input lines count:";
cin >> m;
cout << "input rows count:";
cin >> n;
matrix = new int *[m];
for(int i = 0;i < m;i++)
matrix[i] = new int[n];
cout << endl << "input matrix:" << endl;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
cin >> matrix[i][j];
lines = m;
columns = n;
}
void print_matrix(int **&matrix, int &lines, int &columns)
{
for(int i = 0; i < lines; i++)
{
for(int j = 0; j < columns; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
}
int find_max(int **matrix, int lines, int columns, int &max_count)
{
int max = INT_MIN;
max_count = 0;
for(int i = 0; i < lines; i++)
for(int j = 0; j < columns; j++)
{
if(matrix[i][j] > max)
{
max = matrix[i][j];
max_count = 1;
}
else
if(matrix[i][j] == max)
++max_count;
}
return max;
}
int main()
{
int **matrix = nullptr;
int m=0, n=0, count=0;
input_matrix(matrix, n, m);
cout << endl;
print_matrix(matrix, n, m);
cout << endl;
int max = find_max(matrix, n, m, count);
cout << "max=" << max << " count=" << count << endl;
for(int i = 0; i < n; i++)
delete[]matrix[i];
delete []matrix;
}
As requested by mister Max Langhof I would also like to propose a more modern solution, based on the std::vector container, which does not need pointers and manual memory management. It's a simple class matrix:
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdint>
using namespace std;
class matrix
{
private:
vector<vector<int>> m_data;
public:
matrix(int cols, int rows)
{
m_data.resize(cols);
for(auto &r : m_data)
r.resize(rows);
}
int max_element()
{
int max = INT_MIN;
for(auto &row: m_data)
{
auto maxinrow = *std::max_element(row.begin(), row.end());
if(maxinrow > max)
max = maxinrow;
}
return max;
}
int element_count(int elem)
{
int count = 0;
for(auto &row : m_data)
count += std::count_if(row.begin(), row.end(), [elem](int a){return a == elem;});
return count;
}
friend istream& operator>>(istream &os, matrix &matr);
friend ostream& operator<<(ostream &os, matrix &matr);
};
Input and output operators could be realized like this:
istream& operator>>(istream &os, matrix &matr)
{
for(int i = 0; i < matr.m_data.size(); i++)
{
for(int j = 0; j < matr.m_data[i].size(); j++)
cin >> matr.m_data[i][j];
cout << endl;
}
return os;
}
ostream& operator<<(ostream &os, matrix &matr)
{
for(int i = 0; i < matr.m_data.size(); i++)
{
for(int j = 0; j < matr.m_data[i].size(); j++)
cout << matr.m_data[i][j] << " ";
cout << endl;
}
return os;
}
And a sample of using of this matrix:
int main()
{
int m = 5, n = 4;
matrix matr(m, n);
cout << "input matrix:" << endl;
cin >> matr;
cout << endl << matr;
int max = matr.max_element();
cout << "max: " << max << " count:" << matr.element_count(max) << endl;
}
Checkout something like this
#include <iostream>
#include <set>
#include <vector>
int main() {
int rowsNo, columnsNo;
std::cin >> rowsNo >> columnsNo;
std::vector<int> matrix(rowsNo*columnsNo);
//Creating matrix
for(auto row = 0; row < rowsNo; ++row) {
for (auto column = 0; column < columnsNo; ++column)
std::cin >> matrix[row*columnsNo + column];
}
auto maxValue = -51;
//Finding positions of maximums
std::set<int> linesWithMaxValue;
for (auto position = 0; position < matrix.size(); ++position) {
if(matrix[position] == maxValue)
linesWithMaxValue.insert(position / columnsNo);
else if(matrix[position] > maxValue) {
linesWithMaxValue.clear();
maxValue = matrix[position];
linesWithMaxValue.insert(position / columnsNo);
}
}
//Print info
const auto numberOfMaxValues = linesWithMaxValue.size();
std::cout << "Number of maxiums: " << numberOfMaxValues << std::endl;
std::cout << "Lines that contains maximum:";
for (const auto& lineId : linesWithMaxValue)
std::cout << " " << lineId;
return 0;
}

Reading data from file and performing matrix multiplication in c++

I am new to C++, and am trying to perform a matrix multiplication taking data from a file. But I am unable to get the multiplication part. Someone please help me to fix this.
While am trying to do the multiplication of 2 matrices but am unable to get the output.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string line;
int d[3][3],e[3][3],f[3][3];
int i=0;
int x=0;
int j=0;
string a[20];
string b[20];
string c[20];
ifstream myfile;
myfile.open("numeric.txt");
while(getline (myfile,line))
{
if(line!=" ")
{
a[x]=line;
b[x]=line;
cout<<a[x]<<endl;
x++;
}
}
cout<<"first Matrix"<<endl;
for(i=0;i<3;i++)
{
for(j=0;j<=4;j++)
{
cout<<a[i][j]<<"";
}
cout<<endl;
}
cout<<"Second Matrix"<<endl;
for(i=1;i<4;i++)
{
for(j=0;j<6;j++)
{
cout<<b[i][j]<<"";
}
cout<<endl;
}
cout<<"Multiplication"<<endl;
for(i=0;i<3;i++)
{
for(j=0;j<=3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
cout<<"Multiplication Result"<<endl;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<c[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
Here is a complete example on how you write (fixed size) matrices to a file and how you can build them reading from that file:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main() {
const size_t matrixSize = 3;
//
ofstream matrixOutput("matrix.txt");
for (size_t i = 0; i < matrixSize; i++) {
for (size_t j = 0; j < matrixSize; j++) {
matrixOutput << j*i << ' ';
}
matrixOutput << '\n';
}
for (size_t i = 0; i < matrixSize; i++) {
for (size_t j = 0; j < matrixSize; j++) {
matrixOutput << j*i * 2 << ' ';
}
matrixOutput << '\n';
}
matrixOutput.close();
//
ifstream matrixData("matrix.txt");
size_t matrixInput[matrixSize][matrixSize];
size_t matrixInput2[matrixSize][matrixSize];
size_t position = 0;
size_t number = 0;
while (matrixData >> number) {
const size_t matrixNumber = size_t(floor(position / (matrixSize*matrixSize)));
const size_t row = size_t(floor(position / matrixSize)) % matrixSize;
switch (matrixNumber) {
case 0:
matrixInput[row][position % 3] = number; break;
case 1:
matrixInput2[row][position % 3] = number; break;
}
position++;
}
matrixData.close();
cout << "Matrices: " << endl;
for (size_t i = 0; i < matrixSize; i++) {
for (size_t j = 0; j < matrixSize; j++) {
cout << matrixInput[i][j] << ' ';
}
cout << endl;
}
cout << endl;
for (size_t i = 0; i < matrixSize; i++) {
for (size_t j = 0; j < matrixSize; j++) {
cout << matrixInput2[i][j] << ' ';
}
cout << endl;
}
cout << endl;
cout << "Matrices multiplication: " << endl;
for (size_t i = 0; i < matrixSize; i++) {
for (size_t j = 0; j < matrixSize; j++) {
cout << matrixInput[i][j] * matrixInput2[i][j] << ' ';
}
cout << endl;
}
// ...
}
Note: if you want you can write the matrix size to the file too, so you can retrieve it later and build custom size matrices.

c++ program to print a horizontal bar chart

I want to print a chart by taking integers from console. I have come up with this syntax. Stuck at a conditional statement.
int main() {
int array[10];
int num;
int size = 0;
for(int i = 0; i < 10; i++)
{
cin >> num;
if(num == 0)
{
break;
}
array[i] = num;
size++;
}
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
if(*something goes here*)
cout << "*";
else
cout << " ";
}
cout << endl;
}
return 0;
}
Try this
#include <iostream>
using namespace std;
#define MAX 100
int main() {
int values[MAX];
int size = 0;
while (true) {
int num;
cin >> num;
if (num == 0) break;
else values[size++] = num;
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < values[i]; j++) {
cout << "*";
}
cout << endl;
}
return 0;
}

Gauss Elimination C++ segmentation fault

I'm really stuck with my code for Gauss Elimination in C++, I need to return upper triangular matrix but still only thing I get is Segmentation fault. I know there must be some sort of going of allocated memory but I can't find where.
Code:
#include <iostream>
using namespace std;
double ** allocateDynamicArray(int order){
double ** dynArray = new double *[order];
int cols = order+1;
double *pool = new double [order * cols];
for(int i = 0;i < order; i++, pool += cols){
dynArray[i] = pool;
}
return dynArray;
}
void deallocateDynamicArray(double **dynArray){
delete [] dynArray[0];
delete [] dynArray;
}
void addAndPrintArray(double **dynArray, int order){
cout << "Zadejte prvky pole radu " << order << endl;
for(int i=0; i< order; i++){
for(int j=0; j< order+1; j++){
cout << "Pole[" << i << "][" << j << "]: ";
cin >> dynArray[i][j];
}
}
for(int i=0; i< order; i++){
for(int j=0; j< order+1; j++){
if(dynArray[i][j] < 10 && dynArray[i][j] >= 0){
cout << " ";
}
cout << dynArray[i][j] << " ";
}
cout << endl;
}
}
double ** gaussElimination(double** dynArray, int order){
for(int j=1; j<=order; j++) /*Horni trojuhelnikova matice*/
{
for(int i=1; i<=order; i++)
{
if(i>j)
{
double c=dynArray[i][j]/dynArray[j][j];
for(int k=1; k<=order+1; k++)
{
dynArray[i][k] = dynArray[i][k] - c * dynArray[j][k];
}
}
}
}
return dynArray;
}
int main()
{
cout << "Zadejte rad matice: ";
int order;
cin >> order;
double **arr = allocateDynamicArray(order);
addAndPrintArray(arr, order);
gaussElimination(arr, order);
deallocateDynamicArray(arr);
return 0;
}
Can anyone tell me what's wrong?
The problem is that in C/C++ the first element of an array should have index 0, so your
for(int i=1; i<=order; i++)
should be
for(int i=0; i<order; i++)
in the gaussElimination function.

Passing 3D dynamic array by reference

I'm trying to create a 3D char array with dynamic memory. I create the char*** point in main then pass it to input and everything works fine until the input function returns and i try to repring the same locaton from main. I get "Access violation reading location." Any suggestions?
void input(char ***a, int f, int n)
{
cin >> f;
cin >> n;
a = new char**[f];
for (int i =0; i <f; ++i)
{
a[i]= new char*[n];
for (int j=0; j <n; ++j)
{
a[i][j] = new char[n];
}
}
for (int i =0; i<f; ++i)
{
for (int j=0; j<n; ++j)
{
for (int k = 0; k <n ;++k)
{
a[i][j][k] = '.';
cout << a[i][j][k];}
}
}
cout <<endl << endl<< a[2][5][5]; //test to see is value is '."
}
int main()
{
char ***station = 0;
int floors=0, n=0;
input(station, floors, n);
cout << endl << endl << station[2][5][5];
}