【发布时间】:2012-11-29 17:45:30
【问题描述】:
我有一个这样的方法签名:
vector<int> findRow(string filename);
它输入不同的文件并返回特定的行。我将在许多不同的文件上使用此方法,并且需要跟踪哪个文件返回哪一行。所以我想为每个文件名分配一个唯一的文件编号,然后使用这个文件编号来引用文件及其相应的返回值。我该怎么做呢?我完全迷路了!!
【问题讨论】:
我有一个这样的方法签名:
vector<int> findRow(string filename);
它输入不同的文件并返回特定的行。我将在许多不同的文件上使用此方法,并且需要跟踪哪个文件返回哪一行。所以我想为每个文件名分配一个唯一的文件编号,然后使用这个文件编号来引用文件及其相应的返回值。我该怎么做呢?我完全迷路了!!
【问题讨论】:
如何定义一个结构(甚至是一个类)info,它将文件名和行号作为属性?定义info 的向量。对于每个文件,将名称和行存储在新的info 中,并附加到向量中。这个向量的索引是你想要的数字。
【讨论】:
您可以使用静态局部变量作为计数器,并使用一个或两个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 是你想要的向量中的数字,你从“行”中得到的数字。