I want to make a matrix using vector and instead of int I use obejects of the class Fraction
However, I am trying to add elements to it but with no luck so far.
class Fraction
{
public:
int num;
int den;
friend ostream& operator<< (ostream& os, Fraction& fr);
voidoperator= (const Fraction& fr);
};
ostream& operator << (ostream& os, Fraction& fr)
{
os << fr.num << "/" << fr.den;
return os;
}
void Fraction::operator=(const Fraction& fr)
{
num = fr.num;
den = fr.den;
}
int main()
{
Fraction fr;
int colunas = 2, linhas = 2;
vector<vector<Fraction>> mat(linhas, vector<Fraction>(colunas));
for (int i = 0; i < colunas; ++i)
{
cout << endl << "Coluna " << i + 1 << endl;
for (int j = 0; j < linhas; ++j)
{
int x;
vector<Fraction> temp;
cin >> x;
fr.num = x;
fr.den = 1;
temp.push_back(fr);
mat.push_back(temp);
}
cout << endl;
}
int len = mat.size();
for (int i = 0; i < len; i++)
{
for (int j = 0; j < mat[i].size(); j++)
{
cout << mat[ i ] [ j ].num << " ";
}
cout << endl;
}
}
With this I do iniatialize the matrix but it will only initialize to the rows.
It will be mat[0][0], mat[1][0], mat[1][0], mat[1][0], and if I try to access mat[0][1] it will give me garbage.
I have tried this line mat[i][j] = temp;
but it gives me "no matching operator=" error.
I had to fix mat.size() //missing () on this call @ line 57
and after that it compiled and ran and did things in the forum's compiler.
I don't have the assignment operator problem.
check your compiler flags, are you running pre c++ 17 mode?
With this I do iniatialize the matrix but it will only initialize to the rows.
It will be mat[0][0], mat[1][0], mat[1][0], mat[1][0], and if I try to access mat[0][1] it will give me garbage.
the operator problem comes when I change the line 47 to this mat[i][j] = temp;
1) When you imitialise your mat vector, you're initialising it to already allocate a number of elements (the columns), and, furthermore, you're initialising each of those column vectors to have a number of elements (the lines).
However, later on, when you're putting data into the mat vector, you're not modifying the values of the existing elements - you're using push_back() to add new elements onto the end of those existing vectors, making them bigger.
Do one or the other, not both.
2) A second problem is that, for every single new Fraction object you create, you're creating a whole new vector of fractions (line 39), pushing a single object (the new one) onto that vector (45), and then pushing that vector into your top-level vector as a whole new column (47). Effectively, you're creating a whole new column for every fraction, so that each column has only 1 line.
You meed to rework the logic of your code so that you only create a column where you need to, and add multiple fractions (lines) to the same column.