写在前面:
桌子在那里,我不去搬它,它就不会动。
在B乎等网站,看到C++最大的诟病之处就是库。鉴于此,从当前开始有意识的学习,使用STL库。
这位博主与耐心细致的总结:
原文链接:https://blog.csdn.net/luxiaoyu_sdc/article/details/6416043
我做了word文档,对版式做了一些调整(不知如何上传)
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#if 0
find_if:InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
Returns an iterator to the first element in the range [first,last) for which pred returns true.
If no such element is found, the function returns last.
找一个“什么样的”参数,而不再局限于找“哪一个”参数;
所找的参数格式有一元函数pred决定;输入指针,输出指针(迭代器);
①return last——返回vector的last指针;同时注意这一指针已经越界,故不可访问(不可*last);真确处理方法如下。
#endif
bool FindCharacter(string &tmpstr)
{
//可行,但是find也可以做到;
// string wantedStr = "thr";
// if(0 == wantedStr.compare(tmpstr)){
// return true;
// }
// return false;
//比较好的展现了find_if的优点:可以提出更加细致的查找条件;
cout<<"i am here"<<tmpstr[1]<<endl;
if('h' == tmpstr[1]){
return true;
cout<<"true we are"<<endl;
}
return false;
}
int main()
{
//std::vector<std::string> number{"one"} 直接用元素初始化,
//分配20个空间,每个都初始化为one;再添加元素时,vector自动扩张;
std::vector<std::string> number(20, "one");
number[3] = "three";
number.back() = "nineteen"; //front back直接访问数字,且可以放在等号左边;
auto pdata4 = number.data(); //data访问,直接返回指针,相当于&front;
auto Position = std::find_if(number.begin(), number.end(), FindCharacter); //智能指针会进行强制类型转化,用于指针的推导比较保险;
if(number.end() != Position){
std::cout<<*Position<<std::endl;
}
else {
std::cout<<"error,do not find!!!"<<std::endl;
}
return 0;
}
代码中试着使用了vector;同时不难发现,find_if 较之与find而言,可以查找的更加细致。比如例子中,可以查找第二个字母是“h”的字符串。这些用法实例可以在这里查看:
http://www.cplusplus.com
很好的一个网站,只是例子不太丰富。