【问题标题】:How to assign a counter to every new file name如何为每个新文件名分配一个计数器
【发布时间】:2012-11-29 17:45:30
【问题描述】:

我有一个这样的方法签名:

vector<int> findRow(string filename);

它输入不同的文件并返回特定的行。我将在许多不同的文件上使用此方法,并且需要跟踪哪个文件返回哪一行。所以我想为每个文件名分配一个唯一的文件编号,然后使用这个文件编号来引用文件及其相应的返回值。我该怎么做呢?我完全迷路了!!

【问题讨论】:

    标签: c++ string file-io


    【解决方案1】:

    如何定义一个结构(甚至是一个类)info,它将文件名和行号作为属性?定义info 的向量。对于每个文件,将名称和行存储在新的info 中,并附加到向量中。这个向量的索引是你想要的数字。

    【讨论】:

      【解决方案2】:

      您可以使用静态局部变量作为计数器,并使用一个或两个std::unordered_map 将 id 映射到向量,也可以将 id 映射到文件名:

      std::unordered_map<int, std::vector<int>> id_to_row;
      std::unordered_map<int, std::string> id_to_file;
      
      // This will be the next id to assign to a row/file
      // I.e. the current row-id is `id_counter - 1` if `id_counter > 0`
      // It can also be seen as the number of mappings made (or rows loaded)
      int id_counter = 0;
      
      std::vector<int>& findRow(std::string filename)
      {
          // Do your stuff
          for (...)
          {
              ...
      
              id_to_row[id_counter].push_back(row_value);
      
              ...
          }
      
          // Map the id to the filename as well
          id_to_file[id] = filename;
      
          // Return a reference to the actual vector, while incrementing id value
          return id_to_row[id_counter++];
      }
      

      【讨论】:

      • 我对 some_number 感到困惑。我应该让它全局化并在我的方法之外保留一个计数器吗?
      • @sumrania some_number 是你想要的向量中的数字,你从“行”中得到的数字。
      • 哦,我想我的帖子很混乱。无论返回类型是什么,我都想为每个文件名分配一个唯一的 ID。所以我的号码应该是随着每个新文件名递增的唯一 ID
      • @sumrania 然后使用全局变量,并更改映射。请参阅我编辑的答案。
      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      相关资源
      最近更新 更多