質問

私はこの完全なコードを持っています:

program List;

{$APPTYPE CONSOLE}

{$R *.res}

uses  System.SysUtils,   
      Generics.Collections;

type   
  TMySubList = TList<Integer>;   
  TMyList = TObjectList<TMySubList>; 

var   
  iIndex1, iIndex2: Integer;   
  MyList: TMyList;   
  MySubList: TMySubList; 

begin

 try
    { TODO -oUser -cConsole Main : Insert code here }

    MyList := TMyList.Create;
    try

      for iIndex1 := 1 to 10 do
      begin
        MySubList := TList<Integer>.Create;
        if MyList.Count <> 0 then MySubList :=  MyList.Last;
        MySubList.Add(iIndex1);
        MyList.Add(MySubList);
      end;

      for iIndex1 := 0 to pred(MyList.Count) do
      begin
        for iIndex2 := 0 to pred(MyList[iIndex1].Count) do write(MyList[iIndex1][iindex2]:5);
        writeln;
      end;

    finally
      MyList.Free;
    end;

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);   
  end;

  Readln;

end.

出力として、私は次のようなものを持っている必要があります:

 1                                   // MyList[0]
 1  2                                // MyList[1]
 1  2  3                             // MyList[2]
 1  2  3  4                          // MyList[3]
 1  2  3  4  5                       // MyList[4]
 1  2  3  4  5  6                    // MyList[5]
 1  2  3  4  5  6  7                 // MyList[6]
 1  2  3  4  5  6  7  8              // MyList[7]
 1  2  3  4  5  6  7  8  9           // MyList[8]
 1  2  3  4  5  6  7  8  9  10       // MyList[9]

しかし、私はこの結果を持っています:

 1  2  3  4  5  6  7  8  9  10       // MyList[0]
 1  2  3  4  5  6  7  8  9  10       // MyList[1]
 1  2  3  4  5  6  7  8  9  10       // MyList[2]
 1  2  3  4  5  6  7  8  9  10       // MyList[3]
 1  2  3  4  5  6  7  8  9  10       // MyList[4]
 1  2  3  4  5  6  7  8  9  10       // MyList[5]
 1  2  3  4  5  6  7  8  9  10       // MyList[6]
 1  2  3  4  5  6  7  8  9  10       // MyList[7]
 1  2  3  4  5  6  7  8  9  10       // MyList[8]
 1  2  3  4  5  6  7  8  9  10       // MyList[9]

このエラーが終了すると: einvalidpointer:無効なポインター操作。コードは非常にシンプルですが、私が間違える場所、または私がそれに追加するのを忘れていることを理解していません。この問題を解決するのを手伝ってくれてありがとう

役に立ちましたか?

解決

Mysublistの新しいインスタンスを作成し、ほとんどの場合、既存のリストへのポインターでそれを上書きし、新しいアイテムを追加します。代わりに、前のリストからアイテムを個別にコピーする必要があります。

  for iIndex1 := 1 to 10 do
  begin
    MySubList := TList<Integer>.Create;
    if MyList.Count <> 0 then begin
      for iIndex2 := 0 to MyList.Last.Count-1 do
        MySubList.Add(MyList.Last[iIndex2]);
    end;
    MySubList.Add(iIndex1);
    MyList.Add(MySubList);
  end;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top