C ++ - Removing a vector element referenced by a pointer

Well, I don't know if this is possible, but it will be:

struct stPiece
{
  /* some stuff */
  stPiece *mother; // pointer to the piece that created this one
};

vector<stPiece> pieces;

Is it possible to remove the fragment referred to by the “mother” from the pieces, having only this pointer as a link? How?

Will it mess with other links? (i.e., if it is not the last element of the vector, shifting the following elements to other memory positions, while other "mothers" remain constant). Of course, I assume that all child parts will be deleted (so I will not need to update any pointer that goes to the same mother).

Thank!

+3
source share
5 answers

mother pieces, .

pieces . , , .

: , , , , .

pieces mother, , mother s. pieces - .

std::list pieces mother . std::list , /. mother, , mother, , , boost::shared_ptr .

+2

, , , . . ,

vector<stPiece> pieces; 

stPiece *mother;

vector<stPiece>::size_type i = mother - &pieces[0];
assert(i < pieces.size());

vector<stPiece>::iterator it = pieces.begin() + i;

pieces.erase(it);

.

, , , . . "" , , PITA.

, , ", ".

+2

, , .

, "", , .

, , .

+1

: .

. . , . ( ) ( ), , , .

, :

vector<stPiece*> pieces

/ / . :

  • (/ )
  • ( )
  • , ( ), stPiece

.

+1

, , . , , stPiece s, .

, mother , .

set< stPiece * > all_pieces;

struct stPiece {
    boost::shared_ptr< stPiece > const mother;
    stPiece( boost::shared_ptr< stPiece > &in_mother )
     : mother( in_mother ) {
        all_pieces.insert( this );
    }
    ~stPiece() {
        all_pieces.erase( this );
    }
};

The key point is that there is a difference between the content of some objects and just the ability to iterate over. If you use the most obvious way to create and delete objects does not use the container, they probably should not be in it.

+1
source

Source: https://habr.com/ru/post/1728413/


All Articles