【问题标题】:boost::algorithm::string::finder.hppboost::算法::字符串::finder.hpp
【发布时间】:2013-03-26 17:25:05
【问题描述】:

Already asked this question 并收到了有关 c++ STL 的答案,但是 boost 呢?

这是一个关于 boost Finders 的问题。如果您有可描述的 boost 库实现的链接,我将不胜感激,因为它可以更轻松地为实际应用程序寻找 boost 库。

我的问题是哪个 boost finder 最适用于 lastIndexOf

【问题讨论】:

  • 你能解释一下你的用例吗?为什么需要查找器实例而不是使用标准(或增强)显式函数来查找字符或模式的最后一个索引?如果您只想要一个用于查找模式的最后一个索引的函数,请使用@sftrabbit 发布的解决方案。
  • @ViteFalcon 是的,我正在寻找 boost 中的一个函数,它可以找到模式的最后一个索引并选择使用发布的解决方案。

标签: c++ boost lastindexof


【解决方案1】:

首先,如果您要搜索子字符串的最后一次出现,最简单的选择是使用std::string::rfind

std::string str = "Hello, World!";
int index = str.rfind("o");

如果您需要使用 Boost,因为您希望它适用于通用范围,请使用 boost::algorithm::find_last。它需要两个范围。在第一个范围内搜索第二个范围。

std::string str = "Hello, World!";
iterator_range<std::string::iterator> it = find_last(str, "o");
int index = std::distance(str.begin(), it.begin());

如果您真的想使用查找器,您似乎正在寻找boost::algorithm::last_finder。查找器返回一个以两个迭代器作为参数的函数对象。该函数返回一个iterator_range 你可以这样使用它:

auto finder = last_finder("o");

std::string str = "Hello, World!";
iterator_range<std::string::iterator> it = finder(str.begin(), str.end());
int index = std::distance(str.begin(), it.begin());

【讨论】:

  • 也许现在最简单的事情就是最好的。谢谢你的回答。
  • @Mushy 明确一点,您知道std::string 有一个rfind 成员函数,对吧?如果您只是在字符串中搜索,请使用它。如果您需要处理通用容器,请使用 boost 算法。
  • 是的,我知道 rfind 在指向我原始问题的链接中确定。您是否建议 boost 库是最好的,或者应该只在通用容器上使用?我有一个使用通用和非通用的大型程序。
  • @Mushy 如果您需要做的只是在std::string 中搜索子字符串的最后一次出现,最好使用rfind。但是,如果您需要搜索任何类型的容器,可能是 std::vectorstd::set,您将需要使用 boost 算法。
  • 嗯,好的,谢谢您的澄清。我将代码切换到 rfind,因为我正在搜索 std::string。但是 std::string 不是也包含字符并提供一些标准容器操作的容器吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-13
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
相关资源
最近更新 更多