所以我有以下 lambda 函数来搜索我的字符串 vector 以查找字符串中的某个子字符串。
像一些随机字符串"water""attic""cat""pool"
我想返回所有包含 "at"
的字符串
.
auto iter = std::find_if(myVector.begin(),
myVector.end(),
[subSequence](std::string s) -> bool { return (subSequence == s); });
if ( iter != myVector.end() ){
std::cout << *iter << "\n";
}
我的问题是,将其扩展到遍历整个 vector 的最佳方法是什么?我对此很陌生,我尝试过的一切都不起作用。这是否可行,或者我是否需要考虑其他方法?
最佳答案
试试这个:(更新以匹配更新的问题)
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> myVector = {"cat","bye","what's up?"};
std::string subString = "at";
//Create a lambda function to check if a string contains subString
//Uses s.find(subString), which returns the position of subString in s,
// and checks that it doesn't equal the end of the string
auto containsSubString = [subString](std::string s){
return s.find(subString) != std::string::npos;};
auto iter = std::find_if(myVector.begin(),
myVector.end(),
containsSubString);
//Use a while loop, checking whether iter is at the end of myVector
//Do a find_if starting at the item after iter, std::next(iter)
while (iter != myVector.end())
{
std::cout << *iter << std::endl;
iter = std::find_if(std::next(iter),
myVector.end(),
containsSubString);
}
return 0;
}
预期输出:
cat
what's up?
您的代码问题:
- 您的 lambda 只是将
subSequence
与subSequence
进行比较,因此它始终返回 true。 - 您正确地使用了
std::find_if
,但诀窍是将它放入一个while
循环中,该循环检查您是否已到达 vector 的末尾还没有。 - 虽然在您的 lambda 中包含
-> bool
没有坏处,但这并不是绝对必要的,因为编译器可以从 lambda 的定义中推断出该信息 (s.find(subString ) != std::string::npos
将始终返回 bool)。您只需要在编译器可能不明确类型时明确提及类型(或者如果您想让其他可能阅读您的代码的程序员更加清楚)。
编辑:如@Yakk 的回答所示,使用 std::next(iter)
而不是 iter + 1< 实际上更好
,就像我最初拥有的那样。
这是因为 std::next(iter)
将适用于所有类型的 C++ STL 容器,而仅递增迭代器并不适用于所有容器(尽管它适用于最常见的容器,例如std::array
或 std::vector
).
关于c++ - 将 vector 上的 std::find_if 转换为循环的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33226202/