对SystemVerilog关联数组进行排序的最佳方法是什么?

时间:2014-05-21 17:07:57

标签: sorting associative-array system-verilog

我有一个关联数组,我需要按特定顺序处理该数组中的项目。最好的方法是什么?

这是一个例子。假设我有一个人名的联想数组及其年龄:

int age[string];
age["bob"] = 32;
age["timmy"] = 4;
age["tyrian"] = 31;

我需要将这个数组从最年轻的人处理到最老的人。目前,我正在创建另一个用于索引和排序的数组。

  string sorted_age[$];

  // Is there a more efficient way to do this sort?
  foreach (age[i]) begin
    bit inserted = 0;
    foreach (sorted_age[j]) begin
      if (age[i] < age[sorted_age[j]]) begin
        sorted_age.insert(j, i);
        inserted = 1;
        break;
      end
    end
    if (!inserted) begin
      sorted_age.push_back(i);
    end
  end

EDA Playground的完整示例:http://www.edaplayground.com/x/2_8

2 个答案:

答案 0 :(得分:1)

您可以再添加一个队列,然后使用内置数组方法。我还没有完成性能测试(可能是依赖于模拟器的),但代码行数较少且易于阅读。

  string sorted_age[$];
  int store_age [$];

  store_age = age.unique(); // find all unique ages (no duplicates)
  store_age.sort(); // sort by age
  foreach(store_age[i]) begin
    // multi entry puch_back
    sorted_age = {sorted_age, age.find_index with (item==store_age[i])};
  end

EDA Playground

上的完整示例

答案 1 :(得分:1)

您可以使用sort() with功能:

  // Create an aray of people's names
  string sorted_age[] = new [age.size()];
  int index = 0;
  foreach (age[i]) begin
    sorted_age[index++] = i;
  end

  // Sort the array
  sorted_age.sort() with (age[item]);

EDA Playground的完整示例:http://www.edaplayground.com/x/3Mf