2012-08-31 48 views
0

我在這個問題上很掙扎,而且我還沒有取得任何進展,現在是時候尋求幫助了。我對boost庫的熟悉程度只比表面上略高一點。我試圖通過一個相當大的字符串進行逐行掃描。實際上,它是讀入std :: string對象的文件的全部內容(文件不會很大,它是命令行程序的輸出)。boost :: regex_search拒絕接受我的觀點

該程序的輸出pnputil是重複的。我正在尋找某些模式以努力查找我想要的「oemNNN.inf」文件。本質上,我的算法是找到第一個「oemNNN.inf」,搜索該文件的特徵。如果這不是我想要的那個,請轉到下一個。

在代碼中,它是這樣的:從Boost庫文檔1.47(我使用的版本)

std::string filesContents; 
std::string::size_type index(filesContents.find_first_of("oem")); 
std::string::iterator start(filesContents.begin() + index); 
boost::match_results<std::string::const_iterator> matches; 
while(!found) { 
    if(boost::regex_search(start, filesContents.end(), matches, re)) 
    { 
     // do important stuff with the matches 
     found = true; // found is used outside of loop too 
     break; 
    } 

    index = filesContents.find_first_of("oem", index + 1); 
    if(std::string::npos == index) break; 
    start = filesContents.being() + index; 
} 

我使用this example。有人請向我解釋我的用法與這個例子有什麼不同(除了我沒有將東西存儲到地圖等事實之外)。

從我可以告訴我,我使用的示例使用相同類型的迭代器。然而,當我編譯代碼時,微軟的編譯器告訴我:沒有重載函數boost :: regex_search的實例匹配參數列表。然而,儘管迭代器被命名爲BidiIterator,但intellisense用我使用的參數顯示了這個函數。我不知道這個的意義,但考慮到這個例子,我假設無論BidiIterator是什麼,它都需要一個std :: string :: iterator來進行構造(可能是一個不好的假設,但似乎是有道理的,因爲例)。該示例確實顯示了第五個參數match_flags,但該參數缺省值爲boost :: match_default。因此,這是不必要的。然而,只是爲了踢球和咧嘴笑,我已經添加了第五個參數,但仍然無效。我如何濫用論據?特別是在考慮這個例子的時候。

下面是一個簡單的程序,它演示了沒有循環算法的問題。

#include <iostream> 
#include <string> 

#include <boost/regex.hpp> 

int main() { 
std::string haystack("This is a string which contains stuff I want to find"); 
boost::regex needle("stuff"); 

boost::match_results<std::string::const_iterator> what; 
if(boost::regex_search(haystack.begin(), haystack.end(), what, needle, boost::match_default)) { 
    std::cout << "Found some matches" << std::endl; 
    std::cout << what[0].first << std::endl; 
} 

return 0; 
} 

如果您決定編譯,我正在編譯並鏈接到1.47的boost庫。我正在使用的這個項目廣泛使用這個版本,更新不是由我來決定的。

感謝您的任何幫助。這是最令人沮喪的。

Andy

回答

2

一般來說,迭代器的類型是不同的。從begin()end()

std::string haystack("This is a string which contains stuff I want to find"); 

返回值將是std::string::iterator。 但您的匹配類型是

boost::match_results<std::string::const_iterator> what; 

std::string::iteratorstd::string::const_iterator是不同的類型。 因此,有幾個變種

  1. 聲明串爲const(即const std::string haystack;
  2. 聲明迭代如const_iterators(即std::string::const_iterator begin = haystack.begin(), end = haystack.end();)並將它們傳遞到regex_search
  3. 使用boost::match_results<std::string::iterator> what;
  4. ,如果你有C++ 11可以使用haystack.cbegin()haystack.cend()

example of work

+0

謝謝了!我知道問題必須是一個簡單的問題。我只是浪費了太多時間,需要第二套眼睛。我完全忽略了在函數參數中使用「const std :: string ...」的例子。有一件事:我期望如果字符串對象是const,那麼調用'myString.begin()'將返回一個const迭代器。但是,我實際上必須使用'std :: string :: const_iterator begin(myString.begin());'來使它工作。這是爲什麼? –

+0

@AndrewFalanga正如你所見http://liveworkspace.org/code/57db9afe6464f944f2fecc4d8561ab91 const std :: string.begin()'返回'const_iterator'。 – ForEveR