如何在c ++中的字符串向量中使用find函数? [英] How to use the find function in a string vector in c++?
本文介绍了如何在c ++中的字符串向量中使用find函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在vector类中了解了find函数,我想尝试一下。事实是,当我使用单个单词并使用查找功能时,它可以完美地运行。但是当我在字符串向量中输入诸如This is a line之类的行,然后使用find函数来搜索诸如is之类的单词。它没有显示任何东西。我想知道如何解决这个问题。请帮帮我。
vector< string> vec( 0 );
vec.push_back( Jack);
vec.push_back( 12);
vec.push_back( 这是一行);
if (std :: find(vec.begin(),vec.end(), line)!= vec.end()) // 这不起作用
{
cout<< vector有元素<< endl;
}
解决方案
这是 std :: find $ c的正确行为$ c> mehod,请参阅 std :: find at C ++ reference [ ^ ]。您需要编写其他代码才能找到包含搜索字符串作为子字符串的项目(可能是 std :: find_if [ ^ ]更符合您的需求。)
std :: find
匹配传递给函数的整个值,而不是它的一部分。在函数调用中,向量中的值不匹配行,因此您无法获得匹配。如果你想要一个匹配在子字符串上的find,你必须使用std :: find_if
,它允许你传入谓词而不是使用的std :: string ::运算符==
I learnt about the find function in the vector class and i wanted to give it a try. The fact is that when i use single words and use the find function then it works perfectly. But when i enter a line such as "This is a line" in the string vector and then use the find function to search for a word such as "is". It doesnt show anything. I am wondering how to fix this issue. Please help me out.
vector<string> vec(0);
vec.push_back("Jack");
vec.push_back("12");
vec.push_back("This is a line");
if (std::find(vec.begin(), vec.end(), "line") != vec.end()) // this doesnt work
{
cout<<"vector has the element"<<endl;
}
解决方案
That is the correct behaviour of the std::find
mehod, see std::find at C++ reference[^]. You need to write additional code in order to find items containing the search-string as substring (Possibly std::find_if[^] better fits your needs).
std::find
matches the whole value you pass into the function, not a part of it. In your function call no value in your vector matches "line" so you don't get a match. If you want a find that matches on a substring you'll have to usestd::find_if
that enables you to pass in a predicate instead of usingstd::string::operator==
.
这篇关于如何在c ++中的字符串向量中使用find函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文