使用std :: quare_range查找字符串向量中发生的前缀范围

Using std::equal_range to find the range of prefixes that occur in a vector of strings

本文关键字:前缀 范围 向量 字符串 quare std range 查找 使用      更新时间:2023-10-16

我正在尝试提出一个lambda,该lambda将允许 std::equal_range返回一个搜索字符串作为前缀的范围。因为这可能不是正确的措辞,所以一个例子:

给定字符串向量:

  • c: users andy documents screenshot.jpg
  • c: users bob desktop file.txt
  • c: users bob desktop picture.png
  • c: users bob desktop video.mp4
  • c: users john desktop note.txt

我希望迭代器恢复为

  • c: users bob desktop file.txt和
  • c: users bob desktop video.mp4。

我将如何为std::equal_range编写比较lambda,或者std::equal_range不是此作业的正确工具?

我认为您只需要使比较器仅比较前缀的长度与这样的元素:

std::vector<std::string> v
{
    "C:/users/andy/documents/screenshot.jpg",
    "C:/users/bob/desktop/file.txt",
    "C:/users/bob/desktop/picture.png",
    "C:/users/bob/desktop/video.mp4",
    "C:/users/john/desktop/note.txt",
};
std::sort(std::begin(v), std::end(v));
std::string const prefix = "C:/users/bob/desktop/";
auto lb = std::lower_bound(std::begin(v), std::end(v), prefix);
// For the upper bound we want to view the vector's data as if
// every element was truncated to the size of the prefix.
// Then perform a normal match.
auto ub = std::upper_bound(lb, std::end(v), prefix,
[&](std::string const& s1, std::string const& s2)
{
    // compare UP TO the length of the prefix and no farther
    if(auto cmp = std::strncmp(s1.data(), s2.data(), prefix.size()))
        return cmp < 0;
    // The strings are equal to the length of the prefix so
    // behave as if they are equal. That means s1 < s2 == false
    return false;
});
// make the answer look like we used std::equal_range
// (if that's what's needed)
auto range = std::make_pair(lb, ub);
for(auto itr = range.first; itr != range.second; ++itr)
    std::cout << *itr << 'n';

输出:

C:/users/bob/desktop/file.txt
C:/users/bob/desktop/picture.png
C:/users/bob/desktop/video.mp4

解释为什么这项工作会想象一下将向量进行分类。然后想象一下访问每个元素并将其截断到前缀的长度。您将留下一个排序的向量,没有比前缀更长的元素。那时,简单的std::equal_range将完成您需要的事情。因此,我们要做的就是构造一个比较器,该比较器的行为就像 这些容器元素已被截断为前缀的长度,并在我们的std::equal_range搜索中使用该比较器(或Twin std::lower_bound/upper_bound搜索)。