2011-12-07 6 views
2

次のプロトタイプがあれば、それをC++で実装できますか? 私はC++で実装するための具体的なアイデアを提供できるリソース(書籍、Web)を探しています。あなたが見ることができるように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は、異なるデータ型の各動的要素を保持することができます。 Containerとそれ以降のContainerには、それぞれ異なるフィールド(DBの列)を追加する必要があります。分類されたデータをユーザーに返す手段を提供します。

たとえば、ユーザはint型のElement、double型のElement、Date型のElementを最初の時点でコンテナに追加できます。その後、ユーザーはint型に属するすべての要素を照会します。

+4

[Boost.Variant(http://www.boost.org/libs/variant/)を見ることから始めて、[Boost.Any(http://www.boost.org/libs/どれか/)。 – ildjarn

答えて

1

これはあなたが望むものであるならば、私は知りませんが、それはあなたが必要とするように私には思える:Vector<ElementBase*> vec;

+0

むしろ 'vector 'です。 –

+0

@NikolaiNFetissovはい、コメントありがとうございます。 – FailedDev

+0

私にとっては、 'ElementBase'を仮想デストラクタを持つ空のクラスとして作る必要があるようです。 – q0987

0

一つの方法を:それはあなたのベクトルがなければならないことは言うまでもない

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

これはすべてのクラスのための共通の基底クラスを持つことです。この基本クラスへのポインタをベクトルに格納します。ベクターを反復処理し、破壊時にすべてを解放することを忘れないでください。

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); 
関連する問題