0

新しい構造体配列を含む新しい構造体配列を削除する適切な方法は何ですか?

typedef struct CALF_STRUCTURE
{
    char* Name;
    bool IsBullCalf;
} CALF;

typedef struct COW_STRUCTURE
{
    CALF* Calves;
} COW;

int main( void )
{
    COW* Cows;
    Cows = new COW[ 3 ];                // There are 3 cows.

    Cows[ 0 ].Calves = new CALF[ 2 ];   // The 1st cow has 2 calves.
    Cows[ 1 ].Calves = new CALF[ 1 ];   // The 2nd cow has only 1 calf.
    Cows[ 2 ].Calves = new CALF[ 25 ];  // The 3rd cow has 25 calves. Holy cow!

    Cows[ 2 ].Calves[ 0 ].Name = "Bob"; // The 3rd cow's 1st calf name is Bob.

    // Do more stuff...

さあ、クリーンアップしましょう!しかし...牛と子牛の配列または任意のタイプの構造体配列を削除する適切な方法は何ですか?

最初に、forループ内のすべての牛の子牛の配列を削除する必要がありますか?このような:

// First, delete all calf struct array (cows[x].calves)
for( ::UINT CowIndex = 0; CowIndex != 3; CowIndex ++ )
    delete [ ] Cows[ CowIndex ].Calves;

// Lastly, delete the cow struct array (cows)
delete [ ] Cows;

return 0;
};

または、単に牛の配列を削除して、すべての子牛の配列も削除されることを期待する必要がありますか?このような:

// Done, lets clean-up
delete [ ] Cows;

return 0;
};

または?

4

2 に答える 2

1

ネストされた配列を手動で削除する必要があります。

しかし、C ++を使用しているので、配列を忘れて、次を使用してくださいstd::vector

typedef struct COW_STRUCTURE
{
    std::vector<CALF> calves;
} COW;

int main( void ) {
  std::vector<COW> cows;

効率的でさらに安全な方法ですべてを管理するものを使用してみませんか?

副次的な情報と同じように:

  • タイプ名は通常、すべてが大文字になっているわけではありません(たとえばCowcowまれCOWに)、大文字は定数用です
  • 変数は通常、キャメルケースまたはアンダースコア付きの小文字です(そうでcalvesはありませんCalves
于 2013-01-27T00:53:24.910 に答える
1

ない。C ++でこれを行うには:

struct CALF
{
    std::string Name;
    bool IsBullCalf;
};

struct COW
{
    std::vector<CALF> Calves;
};

そして、でmain

std::vector<COW> Cows(3);

魔法によって、あなたはもはや何も削除する必要はありません。

于 2013-01-27T00:53:42.580 に答える