gpt4 book ai didi

c++ - 创建一个模板,该模板是具有多个变量的自定义数据类型的 vector

转载 作者:行者123 更新时间:2023-11-30 01:59:42 25 4
gpt4 key购买 nike

我必须能够使用下面的命令,其中 T 可以是任何类型,例如字符串。

Counter<T> counter;  

计数器应该能够容纳多个项目,因此我选择将其实现为 vector 。每个项目本身必须包含一个 T 类型的变量(如果我们继续上面的示例,则为一个字符串)和一个 int。我需要使解决方案尽可能简单,因为稍后我将需要创建函数,通过在其他任务中降低 int 值来打印出每个项目。我试过以下代码,但 1) 它不起作用,2) 有更好的解决方案吗?

#include<string>
#include<cstdlib>
#include<vector>

template<class T>
class Record{
T itemtype;
int total;
public:
int increment(T item);
int count(T item);
void printSummary();
};


class Counter{
vector<Record> data;
};

int main(){

Counter<string> counter;

return 0;
}

最佳答案

您的程序包含一些错误,请在下面指出。

小问题:

首先,一件小事:您不需要包含 <cstdlib>标题 - 至少不是你所展示的内容。

#include<string>
// #include<cstdlib> // <== (YOU DON'T SEEM TO NEED THIS)
#include<vector>

第一个问题:

如果你使用非限定名称来引用命名空间中的对象,你应该首先有一个 using允许编译器将这些非限定名称解析为正确的完全限定名称(即包括它们所属的命名空间)的声明。

例如,vectorstring属于std命名空间。因此,您要么以完全限定的形式使用这些名称( std::vectorstd::string ),要么添加适当的 using声明,如下所示:

using std::vector; // USING DECLARATIONS TO ALLOW UNQUALIFIED NAMES SUCH AS
using std::string; // string AND vector TO BE CORRECTLY RESOLVED

第二个问题:

最后,你想要的是让你的类(class)Counter参数化,并且该参数应用于实例化内部 vector .因此,Counter还必须是一个类模板(毕竟这就是您在 main() 函数中使用它的方式):

// MAKE THIS A CLASS TEMPLATE!
template<typename T>
class Counter{
vector<Record<T>> data;
};

结论:

在实现上述所有更正后,您的代码应如下所示:

#include<string>
#include<vector>

using std::vector;
using std::string;

template<class T>
class Record{
T itemtype;
int total;
public:
int increment(T item);
int count(T item);
void printSummary();
};

template<typename T>
class Counter{
vector<Record<T>> data;
};

int main(){

Counter<string> counter;

return 0;
}

这是一个live example显示上面的代码编译。

关于c++ - 创建一个模板,该模板是具有多个变量的自定义数据类型的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15947838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com