初心者の質問、怖いです。配列内の特定の要素の位置(インデックス)を記録する必要があります。次のことを考慮してください。
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
Ten : constant Positive := 10;
type ArrayIndex is new Positive range 1 .. Ten;
type MyRecord is record
firstItem : Integer;
secondItem : Integer;
end record;
TheRecords : array (1 .. Ten) of MyRecord;
indexOfElement50 : ArrayIndex := 1;
begin
-- set the values in TheRecords
for i in TheRecords'Range loop
TheRecords(i).firstItem := i * 10;
TheRecords(i).secondItem := i * 20;
end loop;
-- find which element of TheRecords has a
-- firstItem with a value of 50
for i in TheRecords'Range loop
if TheRecords(i).firstItem = 50 then
-- this next line is horrible: I should
-- not be required to do type casting
-- in a strongly-typed language.
indexOfElement50 := ArrayIndex(i);
exit;
end if;
end loop;
Put(ArrayIndex'image(indexOfElement50));
end Main;
「TheRecordsのどの要素に値が50のfirstItemがあるかを見つける」というコメントに至るまで、すべてが私が抱えている問題を設定しているだけです(もちろん、はるかに大きなプログラムで)。
CとPythonの世界から来ましたが、私はAdaでの強い型付けについて宗教的にしようとしてきました。そのため、「indexOfElement50」を慎重に定義し、firstItemが50であるTheRecordsの要素のインデックスにします。コメントの下で始まるループは、その要素を検索するコードです。そしてそれを見つけます!
しかし、それから私はiをArrayIndexになるようにキャストする必要があります。そして、強く型付けされた世界では、キャストはとても間違っています。indexOfElement50をループパラメーターとして使用しようとしましたが、コンパイラーにはそのいずれもありません。
したがって、indexOfElement50を整数として宣言する(範囲を制限するガイドラインを可能な限り破る)か、型キャストを実行する(Cでは優れていますが、行うべきではない)必要があるようです。強く型付けされた言語)。
または、おそらく、私は本当に明白な何かを見逃しており、これは専門家によって熱心に指摘されます。
アプローチを少し逆にしたいと思います。
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
Ten
値10の名前の定数は本当に必要ありません!後で12にしたい場合はどうしますか?
type MyRecord is record
firstItem : Integer;
secondItem : Integer;
end record;
レコードの配列が必要ですが、必要な期間の決定を延期しましょう...
type Record_Array is array (Positive range <>) of MyRecord;
...そしてテスト配列を定義します。そのサイズはたまたま10ですが、何でもかまいません。
TheRecords : Record_Array (1 .. 10);
(このテストプログラムの)有効な結果はにのみ存在できますがTheRecords’Range
、範囲外の値を追加して「見つかりません」を示しましょう。
subtype Possible_Index is Natural range 0 .. TheRecords'Last;
indexOfElement50 : Possible_Index := 0; -- indicates 'not found'
OK!
begin
-- set the values in TheRecords
for i in TheRecords'Range loop
TheRecords(i).firstItem := i * 10;
TheRecords(i).secondItem := i * 20;
end loop;
-- find which element of TheRecords has a
-- firstItem with a value of 50
for i in TheRecords'Range loop
if TheRecords(i).firstItem = 50 then
indexOfElement50 := i;
exit;
end if;
end loop;
Put_Line (indexOfElement50'Image); -- legal in Ada2012
end Main;
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加