c++ - 缺少 vector 模板参数

标签 c++ templates vector

我正在尝试创建一个类来创建 vector 并对其使用冒泡排序。一切都编译得很好,除了当我尝试创建一个名为 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();

}

最佳答案

BubbleStorage 是一个模板类,需要一个模板参数。

尝试

BubbleStorage<int> bubble;

此外,考虑到此模板参数,请确保在类函数中,您不会假设“int”或“double”甚至“MyClass”使用 T(模板参数)。因此,如果您想要 vector 的迭代器,那么它

vector<T>::iterator //or
vector<T>::const_iterator

add_data 中,您不应假设 T 是 int 可转换的。您应该有一个外部函数来获取随机 T。考虑到这些问题,请确保您确实需要对 BubbleStorage 进行模板化。或者让 add_data 采用 T 而不是 vector 的大小。

关于c++ - 缺少 vector 模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18816031/

相关文章:

c++ - Cuda 从设备内存创建 3d 纹理和 cudaArray(3d)

c++ - 优化弹性字符串文字解析

c++ - 无法理解我的程序的输出

c++ - 尝试验证日期时 undefined reference

java - 你如何在 Play Framework scala 模板中使用 DTO?

c++ - vector 不从 cin 获取输入

python - django 缓存函数是否会生成模板

html - 在 Django 中为 <table> 设置列宽

c++ - 从 vector 到 vector 的过滤操作

c++ - 如何将 std::vector<std::vector<int>> 从 C++ 返回到 C++/CLI?