2015-11-04 222 views
-2

請問我可以指點我在這裏做的錯誤事情嗎?如果字符串以子字符串開頭,使用std :: equal

auto is_start_with = [](std::string const& whole_string, std::string const& starting_substring)->bool{ 
     if (starting_substring.size() > whole_string.size()) return false; 
     return std::equal(begin(starting_substring), end(starting_substring), begin(whole_string)); 
    }; 

它總是返回true。

我知道還有很多其他解決方案,但我想知道這裏的錯誤是什麼。

編輯:

調試運行! enter image description here

P.S.我在其他主文件中直接輸入字符串,並試用它!

編輯2:

我刪除了兩下變換比較之前和它的工作!

std::transform(std::begin(fd_name), std::end(fd_name), std::begin(fd_name), ::tolower); 
std::transform(std::begin(type_id), std::end(type_id), std::begin(type_id_lower), ::tolower); 
+1

向我們展示了一些測試用例,乍一看似乎很確定。 – 101010

+3

看起來[很好](http://coliru.stacked-crooked.com/a/60aa2f0fc14400ad)給我。 – TartanLlama

+0

調試過程中的屏幕截圖被添加了 –

回答

1

我不會用這麼長的標識符像whole_stringstarting_substring。從參數聲明中可以清楚的看到lambda處理字符串。名稱過長會使代碼不易讀。 而且沒有意義使用通用函數std::beginstd::end。 lambda是專門爲字符串編寫的。

你也可以使用只有一個返回statement.`For例如

auto is_start_with = [](std::string const &source, std::string const &target) 
{ 
    return !(source.size() < target.size()) && 
      std::equal(target.begin(), target.end(), source.begin()); 
} 

甚至像

auto is_start_with = [](std::string const &source, std::string const &target) 
{ 
    return (not (source.size() < target.size())) && 
      std::equal(target.begin(), target.end(), source.begin()); 
} 
+0

感謝您的建議 –

+0

@HumamHelfawi完全沒有。你的功能是正確的,但看起來太複雜了。 –

相關問題