C++学习笔记——常用函数积累

1、find函数

find函数用于查找数组中的某一个指定元素的位置。

比如:有一个数组[0, 0, 5, 4, 4];
问:元素5的在什么位置,find函数 返回值 为 2;

find (数组名 + 起始查找元素的位置, 数组名 + 结束查找的元素位置, 想要查找的元素)

find() 函数本质上是一个模板函数,用于在指定范围内查找和目标元素值相等的第一个元素。

如下为 find() 函数的语法格式:

InputIterator find (InputIterator first, InputIterator last, const T& val);

其中,first 和 last 为输入迭代器,[first, last) 用于指定该函数的查找范围;val 为要查找的目标元素。
正因为 first 和 last 的类型为输入迭代器,因此该函数适用于所有的序列式容器。
另外,该函数会返回一个输入迭代器,当 find() 函数查找成功时,其指向的是在 [first, last) 区域内查找到的第一个目标元素;如果查找失败,则该迭代器的指向和 last 相同

代码示例

#include <iostream>     // std::cout
#include <algorithm>    // std::find
#include <vector>       // std::vector
using namespace std;
int main() {
    
    
    //find() 函数作用于普通数组
    char stl[] ="http://c.biancheng.net/stl/";
    //调用 find() 查找第一个字符 'c'
    char * p = find(stl, stl + strlen(stl), 'c');
    //判断是否查找成功
    if (p != stl + strlen(stl)) {
    
    
        cout << p << endl;
    }
    //find() 函数作用于容器
    std::vector<int> myvector{
    
     10,20,30,40,50 };
    std::vector<int>::iterator it;

    it = find(myvector.begin(), myvector.end(), 30);
    if (it != myvector.end())
        cout << "查找成功:" << *it;
    else
        cout << "查找失败";
    return 0;
}

输出

c.biancheng.net/stl/
查找成功:30

2、c_str

语法:
const char *c_str();
c_str()函数返回一个指向正规C字符串的指针常量, 内容与本string串相同.
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。

1.c_str是一个内容为字符串指向字符数组的临时指针;
2.c_str返回的是一个可读不可改的常指针;

注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针

示例代码

string s = "Hello World!";
printf("%s", s.c_str());    // 输出 "Hello World!"

参考:https://www.cnblogs.com/wangduo/p/5858949.html

Guess you like

Origin blog.csdn.net/mao_hui_fei/article/details/120262673