如何在C ++中实现动态元素容器

时间:2011-12-07 22:17:29

标签: c++

鉴于以下原型,是否可以在C ++中实现它? 我正在寻找能够给我一些具体想法的资源(书籍,网络),以便用C ++实现它。

class Container
{
public:
    vector<Element> getElementsByCategory(Category _cate);    
    bool AddElement(Element _element);
    bool DelElement(Element _element);

private:    
    vector<Element> vec;
};

struct Element
{
    Category  cate;
    DataType  type;
    DataValue value;
};

Category can be CategoryA, CategroyB, CategoryC, etc.
DataType can be Date, int, float, double, string, etc.
DateValue is correspoding to DataType.

如您所见,类Container可以保存每种不同数据类型的动态元素。用户负责将每个不同的字段(DB中的列)添加到Container,稍后Container提供将分类数据返回给用户的方法。

例如,用户可以在一开始就将int of int类型元素,双重类型元素和Element of Date类型添加到容器中。然后,用户想要查询属于int类型的所有元素。

2 个答案:

答案 0 :(得分:1)

我不知道这是不是你想要的,但在我看来你需要一个:

template<class Category, class DataType>
struct Element : public ElementBase //so that your container can hold the items
   Category cate;
   DataType type;
   DataType value;
};

不用说,你的矢量应该是:Vector<ElementBase*> vec;

答案 1 :(得分:0)

可以这样做的一种方法是为所有类创建一个公共基类。在向量中存储指向此基类的指针。不要忘记遍历向量并在销毁时释放所有内容。

struct Base {};
class Category : public Base {};
class DataType : public Base {};
class DataValue : public Base {};

std::vector<Base *> data;

data.push_back(new Categroy);
data.push_back(new DataType);
data.push_back(new DataValue);