2010-08-20 95 views
2
std::vector<std::wstring> lines; 
typedef std::vector<std::wstring>::iterator iterator_t; 
iterator_t eventLine = std::find_if(lines.begin(), lines.end(), !is_str_empty()); 

我該如何定義is_str_empty?我不相信助力提供它。C++ is_str_empty謂詞

回答

6

使用mem_fun/mem_fun_ref:

iterator_t eventLine = std::find_if(lines.begin(), lines.end(), 
    std::mem_fun_ref(&std::wstring::empty)); 

如果你希望在字符串不爲空,則:

iterator_t eventLine = std::find_if(lines.begin(), lines.end(), 
    std::not1(std::mem_fun_ref(&std::wstring::empty))); 
3

純STL就夠了。

#include <algorithm> 
#include <functional> 

... 

iterator_t eventLine = std::find_if(lines.begin(), lines.end(), 
           std::bind2nd(std::not_equal_to<std::wstring>(), L"")); 
+0

我還是喜歡mem_fun_ref更好的解決方案,但這個工作。 +1。 – 2010-08-20 17:11:59

3

使用boost ::拉姆達和boost ::綁定,並把它定義爲bind(&std::wstring::size, _1))

+0

這將告訴你哪些字符串不是空的,而不是空的字符串。 – 2010-08-20 17:11:03

+0

他不是要求字符串不爲空嗎?他的代碼暗示如此。 – UncleZeiv 2010-08-20 17:11:52

+0

好點。衛生署! – 2010-08-20 17:12:39

3

您可以使用仿函數:

struct is_str_empty { 
    bool operator() (const std::wstring& s) const { return s.empty(); } 
}; 

std::find_if(lines.begin(), lines.end(), is_str_empty()); // NOTE: is_str_empty() instantiates the object using default constructor 

請注意,如果你想有一個否定,你必須改變函數:

struct is_str_not_empty { 
    bool operator() (const std::wstring& s) const { return !s.empty(); } 
}; 

或者只是使用查找建議由KennyTM。