Problem is to create a std::vector data table (struct MegaTable, from the example below), where items (struct DataItem, from the example below) could have a pointer to the whole data array.
Here is my code:
#include <vector>
struct MegaDataItem;
struct DataItem
{
int a_;
char* ch_;
MegaDataItem* ptr_;
DataItem( int _a, char* _ch, MegaDataItem* ptr )
: a_( _a )
, ch_( _ch )
, ptr_( ptr )
{}
};
typedef std::vector< DataItem > DataTable;
struct MegaDataItem
{
int b_;
DataTable data_;
MegaDataItem( int _b )
: b_( _b )
{
for ( int j = 15; j >= 10; j-- )
{
DataItem item( j, "", this );
data_.push_back( item );
}
}
};
typedef std::vector< MegaDataItem > MegaTable;
int main( int argc, char** argv )
{
MegaTable table;
for ( int i = 0; i < 5; i++ )
{
MegaDataItem megaItem( i );
table.push_back( megaItem );
}
return 0;
}
And debug snapshot from MSVS:

As you can see, ptr_ pointer everywhere equals to 0x0031fccc, but that is not correct! Pointer must consists with correct struct MegaDataItem data, where all struct DataItem‘s exists…
Thanks for the help!
PS. I know that this is not the hard question, but I can’t get it, how to get this things work!
UPDATE (corrected solution):
PS: thnks to jpalecek! 🙂
MegaDataItem( const MegaDataItem& other )
: b_( other.b_ )
{
data_.clear();
DataTable::const_iterator d_i( other.data_.begin() ), d_e( other.data_.end() );
for ( ; d_i != d_e; ++d_i )
data_.push_back( DataItem( (*d_i).a_, (*d_i).ch_, this ) );
}
void operator=( const MegaDataItem& other )
{
b_ = other.b_;
data_.clear();
DataTable::const_iterator d_i( other.data_.begin() ), d_e( other.data_.end() );
for ( ; d_i != d_e; ++d_i )
data_.push_back( DataItem( (*d_i).a_, (*d_i).ch_, this ) );
}
The problem is your
MegaDataItemstructure is not copyable and assignable (if you copy or assign thevectorinMegaDataItem, the back pointers will point to the originalMegaDataItem, which is incorrect). You have to amend that.Particularly, you’ll have to implement the copy-constructor and assignment operator. In these, you have to redirect the
ptr_pointers inDataItems to the newMegaDataItem.Example implementation:
BTW, depending on what
ch_inDataItemmeans, you may want to implement these inDataItem, too.