小工具知识网

当前位置: 首页 > 行业知识 > c++---find()函数

行业知识

c++---find()函数

2026-11-07 22:49:09 来源:互联网转载

目录

  • 1. string类的find函数
  • 2. 下的 find 函数
  • 3. C++ find_if()函数
  • 4. C++ find_if_not()函数
  • 5. map和vector的find

    1. string类的find函数

    string 类的 find() 函数用于在字符串中查找子串或字符。它有多种重载形式,可以用于查找不同类型的子串或字符。

    下面是 find() 函数的几种常用形式:

    size_t find (const string& str, size_t pos = 0) const;size_t find (const char* s, size_t pos = 0) const;size_t find (const char* s, size_t pos, size_t n) const;size_t find (char c, size_t pos = 0) const;

    其中,str为要查找的子串;s为要查找的字符数组;c为要查找的字符;pos为查找的起始位置;n为要查找的字符个数。

    如果查找成功,find()函数返回子串或字符在字符串中第一次出现的位置;否则,返回一个特殊值string::npos,表示查找失败。

    下面这段代码演示了如何使用find()函数在字符串中查找子串或字符:

    #include #include  int main() {    std::string str = "Hello, world!";    std::cout     std::string str = "Hello, world!";    std::string chars = "o!";        // 使用 find_last_of 查找最后一个匹配 chars 中任意一个字符的位置    size_t pos = str.find_last_of(chars);        if (pos != std::string::npos) {        std::cout         std::cout         std::cout         std::cout     std::vector "www", "baidu", "com" };    auto it = find(myvector.begin(), myvector.end(), "com");    if (it != myvector.end())        std::cout       return ((i % 2) == 1);}        return ((i % 2) == 1);}//以函数对象的形式定义一个 find_if() 函数的查找规则class mycomp2 {public:        bool operator()(const int& i) {                return ((i % 2) == 1);        }};int main() {        std::vector 4,2,3,1,5 };    //调用 find_if() 函数,并以 IsOdd() 一元谓词函数作为查找规则        auto it = find_if(myvector.begin(), myvector.end(), mycomp2());        std::cout     std::vector1, 2, 3, 4, 5, 6, 7, 8, 9};    // 查找第一个大于 5 的元素    auto it = std::find_if(numbers.begin(), numbers.end(), [](int x) {        return x  5;    });    if (it != numbers.end()) {        std::cout         std::cout         while (first!=last) {                if (pred(*first)) return first;                ++first;        }        return last;}        return ((i % 2) == 1);}int main() {        std::vector4,2,3,1,5};        //调用 find_if() 函数,并以 mycomp() 一元谓词函数作为查找规则        auto it = find_if_not(myvector.begin(), myvector.end(), mycomp);        std::cout         while (first!=last) {                if (!pred(*first)) return first;                ++first;        }        return last;}    std::map        std::cout         std::cout     std::vector1, 2, 3, 4, 5};    // 查找值为3的元素    auto it = std::find(myVector.begin(), myVector.end(), 3);    if (it != myVector.end()) {        std::cout         std::cout 

上一篇:linux系统elk组件logstash部署

下一篇:饥荒怎么关掉服务器面板?