首页 > 解决方案 > 如何在类型未知的类中拥有通用向量

问题描述

我想要一个使用向量的数组类,其中向量的类型由用户决定。

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>
        }
    }
}

我尝试使用指针和指向指针的指针,但到目前为止没有任何效果。

标签: c++c++11

解决方案


可能您可能需要一个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;
}

推荐阅读