c++ - 如何在类型未知的类中拥有通用向量
问题描述
我想要一个使用向量的数组类,其中向量的类型由用户决定。
class Array {
vector<type> V
int size;
string type;
public:
Array() {
this->size = 0;
this->type = "void";
// V = vector<depending_on_type>(size);
}
Array(int size, string type) {
this->size = size;
this->type = type;
if(type == "int") {
// initialize as vector<int>
}
}
}
我尝试使用指针和指向指针的指针,但到目前为止没有任何效果。
解决方案
可能您可能需要一个templates
. 只需检查下面的代码,它对我有用:
template <class T>
class Array {
std::vector<T> V;
int size;
std::string type;
public:
Array(): size(0),type("void"), V( T() ) {
}
Array(int s, std::string t): size(s), type(t), V( T() ) {
if(type == "int") {
//do-some initialization
V.push_back(100);
V.push_back(200);
}
}
void print_vector() {
std::cout << V[0] << ", " << V[1] << std::endl;
}
};
int main()
{
Array<int> a(10, "int");
a.print_vector();
return 0;
}
推荐阅读
- go - 无法导入 Go 模块
- performance - 如何使用 ghz 可视化 gRPC 测试的实时指标?
- angular - Angular - Webpack definePlugin 变量未定义
- vue.js - 复制到剪贴板不适用于 VueJS 中的 Chrome 浏览器
- vue.js - Vue 3 用提供的 HTML 替换调用 v-html 的 HTML 标签
- kubernetes-ingress - 使用带有 Traefik Ingress for MultiSite 的 Azure 应用程序网关出现随机 502 Bad gateway 错误
- sql - 使用tableau或sql在日期列上方的行字段中填写最近的值最大值
- .net - HttpWebRequest 不会在生产中发送 cookie
- php - PHP - 如何在数据库中搜索加密数据
- javascript - Carousel - 网格间距问题(图像被压缩) - CSS - 使用 Unbounce(它可以让您构建网站)