zoukankan      html  css  js  c++  java
  • c++中transform()函数和find()函数的使用方法。

    1.transform函数的使用

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

    以下是std::transform的两个声明,

    一元操作:

    template <class InputIterator, class OutputIterator, class UnaryOperation>

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

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

    op可以是函数指针或函数对象或lambda表达式。

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

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

    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)

  • 相关阅读:
    vue开发chrome扩展,数据通过storage对象获取
    Vue手动集成less预编译器
    Google Translate寻找之旅
    Javascript Range对象的学习
    Javascript Promises学习
    SublimeText 建立构建Node js系统
    We're sorry but demo3 doesn't work properly without JavaScript enabled. Please enable it to continue.
    npm安装包出现UNMET DEPENDENCY报错
    (转载)命令行说明中格式 尖括号 中括号的含义
    Linux重启网卡服务Failed to start LSB: Bring up/down networking.
  • 原文地址:https://www.cnblogs.com/mydomain/p/9984482.html
Copyright © 2011-2022 走看看