gpt4 book ai didi

d - 如何删除关联数组中最近最少访问的键?

转载 作者:行者123 更新时间:2023-12-04 02:44:05 25 4
gpt4 key购买 nike

我有一个限制为 x 个键的关联数组,我想删除最近最少访问的键以便添加另一个。我在 mintl 中找到了 HashAA,它可以在 D1 中完成这项工作,但我在 D2 中找不到任何东西。现在是否有任何支持此功能的东西,或者我是否需要维护第二个阵列才能完成工作?

最佳答案

我没有真正的答案,但我认为在几分钟内尝试并实现它会很有趣(它可能效率很低,而且可能有错误):

import std.stdio;
import std.traits;

struct MyHash(AA, size_t Limit)
if (isAssociativeArray!AA)
{
alias KeyType!AA Key;
alias ValueType!AA Value;

void opIndexAssign(Value value, Key key)
{
if (hash.length >= Limit)
{
Key leastUsed = leastUsedKey;
hash.remove(leastUsed);
counts.remove(leastUsed);
}

hash[key] = value;
}

Value opIndex(Key key)
{
counts[key]++;
return hash[key];
}

Value[Key] hash;
alias hash this;

private:

@property Key leastUsedKey()
{
Key result;
size_t maxCount = size_t.max;

foreach (key; hash.byKey)
{
if (auto count = key in counts)
{
if (*count < maxCount)
{
maxCount = *count;
result = key;
}
}
else
{
return key;
}
}

return result;
}

size_t[Key] counts;
}

// just to avoid declaring variables in main()
@property void consume(int key) { }

void main()
{
MyHash!(int[int], 3) hash;

hash[0] = 0;
hash[1] = 0;
hash[2] = 0;

writeln(hash.keys);

hash[2].consume;
hash[5] = 0;

writeln(hash.keys); // 2 stays, 5 added

hash.clear();
hash[0] = 0;
hash[1] = 0;
hash[2] = 0;

hash[0].consume;
hash[1].consume;
hash[1].consume;
hash[2].consume;
hash[2].consume;
hash[2].consume;

hash[5] = 0;
writeln(hash); // (0 removed)
}

关于d - 如何删除关联数组中最近最少访问的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12664621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com