Push_back()不适用于自定义数据类型(模板类)

push_back() not working for custom data type (template class)

本文关键字:定义数据类型 不适用 back Push 适用于      更新时间:2023-10-16

显然push_back()对我的自定义数据类t不起作用,在编译时我得到以下错误:

错误:调用Vector::push_back(int&)没有匹配的函数

谁能给我解释一下这是为什么?谢谢你。
#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";
}

问题出在这一行:

userin.push_back(n);

,其中n为整型。push_back期望t类型的东西

我也不确定在这种情况下T类的意义是什么