我正在尝试创建一个类,它将创建一个向量并对其使用冒泡排序。除非我尝试创建名为bubble的BubbleStorage类,否则所有内容都可以正常编译。
编译器给出了一个错误“在冒泡之前缺少模板参数”,“预期;在冒泡之前”。
此代码尚未完成;但是,因为我仍然在制作冒泡排序功能。我只想在继续之前处理这个问题。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <vector>
using namespace std;
template<typename T>
class BubbleStorage
{
public:
BubbleStorage();
~BubbleStorage();
vector<T>MyVector;
void add_data(int size)
{
srand (time(NULL));
for (T i = 0; i <= size; i++)
random = rand() % 100;
MyVector.push_back(random);
}
void display_data()
{
cout<<"The Vector Contains the Following Numbers"<<endl;
for (vector<int>::iterator i = MyVector.begin(); i != MyVector.end(); ++i)
cout<<' '<< *i;
}
void max()
{
}
void min()
{
}
};
int main(int argc, char *argv[])
{
srand (time(NULL));
int size = rand() % 50 + 25;
BubbleStorage bubble;
bubble.add_data(size);
bubble.display_data();
}
答案 0 :(得分:1)
BubbleStorage是一个模板化的类,需要一个模板参数。
试
BubbleStorage<int> bubble;
同样给出了这个模板参数,请确保在类函数中不假设“int”或“double”甚至“MyClass”使用模板参数T.所以如果你想要一个向量的迭代器
vector<T>::iterator //or
vector<T>::const_iterator
在add_data
中,您不应该假设T
是可转换的。你应该有一个外部函数来抓取随机T
。鉴于这些问题,请确保您确实需要BubbleStorage
进行模板化。或者add_data
取T
而不是矢量大小。