我正在尝试使用TFPGmap创建和使用一个简单的字典:
program rnTFPGmap;
{$mode objfpc}
uses fgl;
var
mydict: specialize TFPGmap<string, string>;
key: string;
i: longint;
begin
mydict.create;
mydict.add('k1','v1');
mydict.add('k2','v2');
mydict.add('k3','v3');
//for key in mydict.keys do {does not work either;}
for i := 1 to length(mydict) do {line 17: first error from here. }
writeln(mydict[i]);
end.
但是,它给出了以下错误:
$ fpc soq_rntfpgmap
Free Pascal Compiler version 3.0.0+dfsg-11+deb9u1 [2017/06/10] for x86_64
Copyright (c) 1993-2015 by Florian Klaempfl and others
Target OS: Linux for x86-64
Compiling soq_rntfpgmap.pas
soq_rntfpgmap.pas(17,16) Error: Type mismatch
soq_rntfpgmap.pas(18,19) Error: Incompatible type for arg no. 1: Got "LongInt", expected "ShortString"
soq_rntfpgmap.pas(22) Fatal: There were 2 errors compiling module, stopping
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
编辑:我试图根据文档修改代码,并提出了以下版本:
program rnTFPGmap;
{$mode objfpc}
uses fgl;
type
tuple = specialize TFPGmap<string, string>;
mydict = Array of tuple;
var
dict: mydict;
i: tuple;
item: string;
begin
setlength(dict, length(dict)+3);
dict.add('k1','v1'); {error on this line: "CREATE" expected but "ADD" found}
dict.add('k2','v2');
dict.add('k3','v3');
writeln('dict.count: ', dict.count);
for i in dict do
writeln(i);
end.
但是我现在遇到以下错误:
$ fpc soq_rntfpgmap
Free Pascal Compiler version 3.0.0+dfsg-11+deb9u1 [2017/06/10] for x86_64
Copyright (c) 1993-2015 by Florian Klaempfl and others
Target OS: Linux for x86-64
Compiling soq_rntfpgmap.pas
soq_rntfpgmap.pas(13,25) Warning: Variable "dict" of a managed type does not seem to be initialized
soq_rntfpgmap.pas(14,7) Fatal: Syntax error, "CREATE" expected but "ADD" found
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
无法解决此问题。
答案 0 :(得分:1)
以下代码有效。请参阅注释以获取一些解释:
program rnTFPGmap;
{$mode objfpc}
uses fgl;
type
Rndict = specialize TFPGmap<string, string>;{define type under type}
var
dict: Rndict; {define object under var}
i: integer;
{main: }
begin
dict := Rndict.Create; {create object in main}
dict.add('k1','v1');
dict.add('k2','v2');
dict.add('k3','v3');
for i := 0 to (dict.count-1) do begin
writeln('i: ',i, '; key: ', dict.getkey(i), '; value: ', dict.getdata(i));
end;
end.
输出:
i: 0; key: k1; value: v1
i: 1; key: k2; value: v2
i: 2; key: k3; value: v3
感谢@DavidHeffernan的指导。