vendredi 1 décembre 2023

Class with vector of another class doesn't like to change its values

I have a class called intClass that contains a private vector of ints and functions to modify its contents. I have another class called intClassClass that contains a private vector of intClasses and functions to modify and print those. When I attempt to change the innermost ints from the intClassClass, the function runs but the ints don't actually change. I'm pretty sure the solution has something to do with a vector making a copy of the object instead of the object itself, but I'm not sure where that happens or how to fix it.

class intClass
{
private:
    vector<int> ints;
public:
    intClass()
    {
        ints.clear();
    }
    intClass(vector<int> iVec)
    {
        ints = iVec;
    }
    void modifyVec(int newInt, int index)
    {
        cout << "modified vec" << endl;

        ints[index] = newInt;
    }
    void printVec()
    {
        for (int i : ints)
        {
            cout << i << ' ';
        }
        cout << '\n';
    }
    int getInt(int index)
    {
        return ints[index];
    }
};
class intClassClass
{
private:
    vector<intClass> ics;
public:
    intClassClass(vector<intClass> icVec)
    {
        ics = icVec;
    }
    intClass getIC(int index)
    {
        return ics[index];
    }
    void printVec()
    {
        for (intClass i : ics)
        {
            i.printVec();
        }
        cout << '\n';
    }
};

int main()
{
    intClassClass icc = intClassClass({ intClass({ 1,3,4,5,21 }), intClass({2, 4 }) });
    icc.printVec();
    icc.getIC(1).modifyVec(3, 0);
    icc.printVec();
    cout << icc.getIC(1).getInt(0);

    return 0;
}

this outputs this

Aucun commentaire:

Enregistrer un commentaire