显然push_back()无法用于我的自定义数据类T。在编译时,出现以下错误:



有人可以向我解释为什么吗?谢谢。

#include <std_lib_facilities>
#include <numeric>
#include <vector>
#include <string>

// vector<int> userin;
// int total;
// bool success;

class T
{
public:
    void computeSum(vector<T> userin, int sumamount, T& total, bool& success);
    void getData(vector<T> userin);
};

template <class T>
void computeSum(vector<T> userin, int sumamount, T& total, bool& success)
{

    if (sumamount < userin.size()){
        success = true;
        int i = 0;
        while (i<sumamount){
            total = total + userin[i];
            ++i;
        }
    } else {
        success = false;
        cerr << "You can not request to sum up more numbers than there are.\n";
    }

}

template <class>
void getData(vector<T> userin)
{
    cout << "Please insert the data:\n";
    int n;

    do{
        cin >> n;
        userin.push_back(n);
    } while (n);

    cout << "This vector has " << userin.size() << " numbers.\n";
}

int helper()
{
    cout << "Do you want help? ";
    string help;
    cin >> help;
    if (help == "n" || help == "no"){
        return 0;
    }else{
        cout << "Enter your data. Negative numbers will be added as 0. Ctrl-D to finish inputing values.\n";
    }
}

int main()
{
    helper();
    getData(userin);

    cout << "How many numbers would you like to sum?";
    int sumamount;
    cin >> sumamount;
    computeSum(userin, sumamount);
    if (success = true) {
        cout << "The sum is " << total << endl;
    } else {
        cerr << "Oops, an error has occured.\n";
    }

    cout << endl;
    return 0;
}

最佳答案

除了某些令人反感的冒犯性问题(例如,应该是template <class T>,而不是template<class>)之外,真正的问题是vector希望您回退T类型的对象。看来您正在使用int类型进行读取并进行推送。尝试:

template <class>
void getData(vector<T> userin)
{
    cout << "Please insert the data:\n";
    T n;

    do{
        cin >> n;
        userin.push_back(n);
    } while (n);

    cout << "This vector has " << userin.size() << " numbers.\n";
}

关于c++ - push_back()不适用于自定义数据类型(模板类),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7643270/

10-11 22:39
查看更多