Push_back()不适用于自定义数据类型(模板类)
push_back() not working for custom data type (template class)
显然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类的意义是什么
相关文章:
- 错误 - 自定义数据类型作为有效负载,带有提升::几何
- C++哈希表 - 如何解决自定义数据类型作为键的unordered_map冲突?
- 从自定义数据类型向量中删除重复元素
- C++:自定义数据类型向量错误的队列
- 交换未定义数据类型中的字节顺序
- 在 C++ 中设置的用户定义数据类型
- C++ - 按自定义数据类型向量的值删除元素
- 使用算法标头查找自定义数据类型的minmax
- 如何将自定义数据类型(用std::对填充的std::数组)写入文件流
- 解析一般CSV读取功能时,如何处理不同的数据类型?(不明确指定它们)
- 从自定义数据类型向量数组C 删除
- 模板函数实例化 自定义数据类型的问题
- 我可以让我自己的自定义数据类型比C++中的数据类型大吗
- 使用QStandardItem传输自定义数据(类型*)时内存泄漏
- C++中的"auto"是否可以识别自定义数据类型?
- C++指向函数作为参数的指针.数据类型不兼容
- 从自定义数据类型列表中删除时出现 C2678 错误
- 用于查询自定义数据类型列表的SQLite虚拟表
- 重载赋值运算符:不同的数据类型-不可能
- 在c++程序中,哪种数据类型不能作为异常抛出