使用std :: quare_range查找字符串向量中发生的前缀范围
Using std::equal_range to find the range of prefixes that occur in a vector of strings
我正在尝试提出一个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
搜索)。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 不计算一个范围内的完美数
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 为带有带前缀的字符串的容器查找相等的范围
- 使用std :: quare_range查找字符串向量中发生的前缀范围
- 为什么命名空间中的某些函数可以在没有命名空间范围前缀的情况下访问