How to efficiently resolve Associative Arrays not being sorted?

Steven Schveighoffer schveiguy at gmail.com
Tue Jun 2 20:52:04 UTC 2020


On 6/2/20 3:32 AM, BoQsc wrote:
> I want to read a file, put it into an array, make some search and 
> replace on the content and output the modified text. However Associative 
> Arrays seem to be unsorted by default. Should I drop the Associative 
> Arrays and use something else? What are the ways to resolve this 
> randomness in Associative Arrays?
> 
> ReadfileAndCopyContentIntoArray.d
>> import std.stdio;
>>
>> int lineNumber = 0;
>> char[][int] fileInArray;
>>
>> void main(){
>>     File exampleFile = File("exampleText.txt");
>>     foreach(line; exampleFile.byLine){
>>
>>         lineNumber++;
>>         fileInArray[lineNumber] ~= line;
>>
>>     }
>>     writeln(fileInArray);
>> }

I have to ask because I don't know if this is similar to your true use 
case or not -- but why would you use an AA when you have an ordered list 
with keys that go from 0 to N? Why not just use an array?

As others have said, RedBlackTree can be used as an ordered map (though 
this requires some definition of a mapping on top of it).

-Steve


More information about the Digitalmars-d-learn mailing list