c++中transform()函数和find()函数的使用方法。

1.transform函数的使用函数

transform在指定的范围内应用于给定的操做,并将结果存储在指定的另外一个范围内。transform函数包含在<algorithm>头文件中。spa

如下是std::transform的两个声明,指针

一元操做:code

template <class InputIterator, class OutputIterator, class UnaryOperation>orm

OutputIterator transform (InputIterator first1, InputIterator last1,OutputIterator result, UnaryOperation op);
对象

对于一元操做,将op应用于[first1, last1]范围内的每一个元素,并将每一个操做返回的值存储在以result开头的范围内。给定的op将被连续调用last1-first1+1次。blog

op能够是函数指针或函数对象或lambda表达式。字符串

例如:op的一个实现 即将[first1, last1]范围内的每一个元素加5,而后依次存储到result中。string

int op_increase(int i) {return (i + 5)};
调用std::transform的方式以下:it

std::transform(first1, last1, result, op_increase);
二元操做:

template <class InputIterator1, class InputIterator2,class OutputIterator, class BinaryOperation>
OutputIterator transform (InputIterator1 first1, InputIterator1 last1,InputIterator2 first2, OutputIterator result,BinaryOperation binary_op);

对于二元操做,使用[first1, last1]范围内的每一个元素做为第一个参数调用binary_op,并以first2开头的范围内的每一个元素做为第二个参数调用binary_op,每次调用返回的值都存储在以result开头的范围内。给定的binary_op将被连续调用last1-first1+1次。binary_op能够是函数指针或函数对象或lambda表达式。

例如:binary_op的一个实现即将first1和first2开头的范围内的每一个元素相加,而后依次存储到result中。

int op_add(int, a, int b) {return (a + b)};
调用std::transform的方式以下:

std::transform(first1, last1, first2, result, op_add);

案例:

std::string s("Welcome");
    std::transform(s.begin(), s.end(), s.begin(),
        [](unsigned char c) { return std::toupper(c); });
    std::cout << s << std::endl; // WELCOME
 
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
    std::cout << s << std::endl; // welcome

2.find 函数的使用

a.find()

查找第一次出现的目标字符串:

string s1 = "abcdef";

string s2 = "ef";

int ans = s1.find(s2) ;   //在S1中查找子串S2

b.find_first_of()

查找子串中的某个字符最早出现的位置,find()是全匹配,find_first_of()不是全匹配.

string str("hi world");

string::size pos=str.find_first_of("h");

if(pos!=string::npos)  //或if(pos!=-1) 

{..

....// 查找到了

} //不存在是find返回string::npos(-1)

相关文章
相关标签/搜索