简体   繁体   English

在 C++ 中将对象添加到 2D Vector

[英]Adding objects to 2D Vector in C++

I want to make a matrix using vector and instead of int I use objects of the class Fraction .我想使用 vector 制作一个矩阵,而不是 int 我使用类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);
    void operator= (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] , and if I try to access mat[0][1] it will give me garbage.它将是mat[0][0]mat[1][0] ,如果我尝试访问mat[0][1]它会给我垃圾。

I have tried this line我试过这条线

mat[i][j] = temp;

but it throws an error:但它抛出一个错误:

no matching operator =没有匹配的运算符 =

Edit: following a suggestion and changing the code accordingly编辑:遵循建议并相应地更改代码

class Fraction
{
public:
    int num;
    int den;

    friend ostream& operator<< (ostream& os, Fraction& fr);
    void operator= (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));
    vector<Fraction> temp;
    for (int i = 0; i < colunas; ++i)
    {
        cout << endl << "Coluna " << i + 1 << endl;

        for (int j = 0; j < linhas; ++j)
        {
            int x;

            cin >> x;

            fr.num = x;
            fr.den = 1;

            temp.push_back(fr);
        }

        mat.push_back(temp);

        cout << endl;
    }

    //cout << mat[0][1];
    //cin.get();
    //cin.get();

    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;
    }
}

What I want the code to do is the following:我希望代码执行以下操作:

when I run it this is how it behaves当我运行它时,这就是它的行为方式

input输入

34
3
2
4

output输出

34 3
34 3 2 4

That is not the output I expect however, the first two input numbers make up the first column and second two make up the second column.然而,这不是我期望的输出,前两个输入数字构成第一列,后两个输入数字构成第二列。 So the output should be like this:所以输出应该是这样的:

Expected output预期输出

34 2
3 4

If I access mat[0][1] I expect it to give me 2/1 but instead it gives me 3/1如果我访问mat[0][1]我希望它给我2/1但它给我3/1

The vector constructor used in this line:此行中使用的vector构造函数:

vector<vector<Fraction>> mat(linhas, vector<Fraction>(colunas));

fills the vector with linhas copies of vector<Fraction>(colunas) , which itself is a vector of colunas many default-constucted Fraction s.vector<Fraction>(colunas) linhas副本填充向量,它本身是许多默认构造的Fractioncolunas向量。

Faction 's default constructor is implicitly defined (because you did not declare any constructor yourself) and it does nothing. Faction的默认构造函数是隐式定义的(因为您自己没有声明任何构造函数)并且它什么都不做。 It leaves the int members with indeterminate values.它使int成员具有不确定的值。

push_back later adds new elements to the vectors, after the ones that are already there from the default constructed ones. push_back稍后将新元素添加到向量中,在默认构造的元素中已经存在的元素之后。 push_back does not replace elements already in the vector. push_back不会替换向量中已有的元素。

You probably don't want to prefill the vector with default constructed elements, so just default-initialize mat , which will leave it empty.您可能不想使用默认构造元素预填充向量,因此只需 default-initialize mat ,这将使其留空。 The later push_back calls will add elements to it:稍后的push_back调用将向其添加元素:

vector<vector<Fraction>> mat;

As mentioned in the comments, you don't need to write a copy assignment operator.正如评论中提到的,您不需要编写复制赋值运算符。 The compiler will generate one automatically for you that has the correct behavior.编译器会自动为你生成一个具有正确行为的。


If you want to avoid creating Fraction objects with uninitialized values, such as you do in the mat constructor, then you can write your own constructor (which will disable the implicitly declared one), eg:如果您想避免创建带有未初始化值的Fraction对象,例如您在mat构造函数中所做的,那么您可以编写自己的构造函数(这将禁用隐式声明的构造函数),例如:

class Fraction
{
public:
    int num;
    int den;

    Fraction(int num_, int den_) : num(num_), den(den_) {}

    friend ostream& operator<< (ostream& os, Fraction& fr);
    void operator= (const Fraction& fr);
};

//...

        for (int j = 0; j < linhas; ++j)
        {
            int x;
            vector<Fraction> temp;
            cin >> x;

            temp.push_back(Fraction(x, 1));

            mat.push_back(temp);
        }

Instead of temp.push_back(Fraction(x, 1));而不是temp.push_back(Fraction(x, 1)); you can also write just temp.push_back({x, 1});你也可以只写temp.push_back({x, 1}); or temp.emplace_back(x, 1);temp.emplace_back(x, 1); . .


You probably also intend to collect one inner vector in the inner loop and add it to the outer vector, ie:您可能还打算在内部循环中收集一个内部向量并将其添加到外部向量中,即:

    for (int i = 0; i < colunas; ++i)
    {
        cout << endl << "Coluna " << i + 1 << endl;

        vector<Fraction> temp;
        for (int j = 0; j < linhas; ++j)
        {
            int x;
            cin >> x;

            temp.push_back(Fraction(x,1));
        }
        mat.push_back(temp);

        cout << endl;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM