2013-03-26 55 views
2

Already asked this question並收到有關C++ STL的答案,但是boost呢?boost :: algorithm :: string :: finder.hpp

這是一個關於boost搜索器的問題。如果你有一個鏈接到可描述的boost庫實現,我將不勝感激它使得爲實際應用尋找boost庫變得更容易。

我的問題是哪個助手發現最適用於lastIndexOf

+0

你能解釋你的用例嗎?爲什麼你需要一個查找器實例,而不是使用標準(或增強)顯式函數來查找字符或模式的最後一個索引?如果您只想要一個可用於查找模式的最後一個索引的函數,請使用已發佈的解決方案@sftrabbit。 – 2013-03-26 17:45:56

+0

@ViteFalcon是的,我正在尋找一種功能在增強,發現模式的最後一個索引,並選擇使用解決方案張貼。 – Mushy 2013-03-26 17:54:53

回答

2

好第一關,如果你要搜索一個子字符串最後一次出現的最簡單的選擇是使用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()); 
+0

也許最簡單的事情是現在最好的。謝謝您的回答。 – Mushy 2013-03-26 17:47:02

+0

@Mushy爲了清楚起見,你知道'std :: string'有'rfind'成員函數,對吧?如果你只是在字符串中搜索,請使用它。如果您需要處理通用容器,請使用'boost'算法。 – 2013-03-26 17:51:14

+0

是的,我知道在我原來的問題鏈接確定的rfind。您是否建議boost庫最好,或者應該只用於通用容器?我有一個大型項目,既使用通用的, – Mushy 2013-03-26 17:57:51

相關問題