首页 > 解决方案 > 如何循环遍历多维数组的元素并搜索匹配项?

问题描述

如何循环遍历数组 (recarr1) 的元素?我的目标是我想找到一个匹配的 f1 值,然后输出相关的 f2 值。阵列必须存储为 ROM。

这个问题来自一本书,与现实世界的应用程序无关。

library ieee;
use ieee.std_logic_1164.all;

entity recordtest is
port(
address: in integer range 0 to 15;
data_out : out std_logic_vector(7 downto 0));
end entity;

architecture recorder of recordtest is

type t_rec1 is record                  -- Declare a record with two fields
   f1 : std_logic_vector(15 downto 0);
   f2 : std_logic_vector(15 downto 0);
end record t_rec1;

type t_rec1_array is array (natural range 0 to 255) of t_rec1;

constant recarr1 : t_rec1_array := (
   1      => (f1 => x"0111", f2 => x"0111"),
   2      => (f1 => x"0011", f2 => x"0111"),
   others => (f1 => x"1111", f2 => x"0111"));

begin


end architecture;

标签: vhdl

解决方案


您应该能够简单地遍历数组并搜索第一个匹配项:

function get_f2 (f1 : std_logic_vector(15 downto 0)) return std_logic_vector is
  variable result : std_logic_vector(15 downto 0);
begin
  result := (others => 'X');

  for i in recarr1'range loop
    if (recarr1(i).f1 = f1) then
      result := recarr1(i).f2;
      exit;
    end if;
  end loop;

  return result;
end function get_f2;

请注意,这是一种“蛮力”方法。它将在一个周期内运行。但是,如果您的阵列/ROM 太大,那么这当然行不通。在这种情况下,您将需要一个设计,该设计在每个周期尝试一个/几个条目,并在完成搜索时发出信号。

recarr1数组可以存储在 ROM 中,因为它是只读的。它不受此功能的任何影响。

我想您的示例中缺少一些东西,因为我不清楚您从哪里获得f1该函数的输入。


推荐阅读