Dodande
Dodande

Reputation: 99

How to copy a list with reference so the changes to the copied version also apply to the original one in C++?

In my homework I have to make the FooCl class for these:

int main()
{
    int x[] = {2, 3, 7, 9, 21, 11, 54, 91};
    FooCl<int> itemsI(x, sizeof(x) / sizeof(x[0]));

    std::string s[] = {"Car", "Bus", "Taxi", "Bike"};
    FooCl<std::string> itemsS(s, sizeof(s) / sizeof(s[0]));

    itemsI.mySort();
    itemsS.mySort();

    if (x[1]!=3 || x[2]!=7 || x[5]!=21 ||
            s[1]!="Bus" || s[2]!="Car" || s[3]!="Taxi") //Notice that x and s don't start sorted, but the if expects them to be sorted after calls to itemsI.mySort() and itemsS.mySort()
    {
        std::cout << "You failed" << std::endl;
    }else{
        std::cout << "You did great" << std::endl;
    }
}

The goal is to make the if function return "You did great". In this task, it is forbidden to change anything in the main function, and I am only allowed to create the FooCl class. The sorting and the validations are calling different elements, so I think I have to use some kind of reference (shallow copy), but I am not sure how to.

Here is my code so far:

template <typename T>
class FooCl
{
private:
    T mItems;
    int mItemsSize;

public:
    FooCl(T (&items)[], int itemsSize)
    {
        this->mItemsSize = itemsSize;
        this->mItems = items;
    };

    ~FooCl(){}

    void mySort()
    {
        std::sort(mItems, mItems + mItemsSize);
    }
};

int main()
{
    int x[] = {2, 3, 7, 9, 21, 11, 54, 91};
    FooCl<int> itemsI(x, sizeof(x) / sizeof(x[0])); //error: no matching function for call to 'FooCl<int>::FooCl

    std::string s[] = {"Car", "Bus", "Taxi", "Bike"};
    FooCl<std::string> itemsS(s, sizeof(s) / sizeof(s[0]));

    itemsI.mySort(); 
    itemsS.mySort();

    if (x[1]!=3 || x[2]!=7 || x[5]!=21 ||
            s[1]!="Bus" || s[2]!="Car" || s[3]!="Taxi")
    {
        std::cout << "false" << std::endl;
    }
    else
    {
        std::cout << "true" << std::endl;
    }
}

At the moment I am getting a compilation error:

    no matching function for call to 'FooCl<int>::FooCl

Upvotes: 1

Views: 52

Answers (0)

Related Questions