簡體   English   中英

將std :: find_if與std :: string一起使用

[英]using std::find_if with std::string

我在這里很傻但是在迭代字符串時我無法獲得謂詞的函數簽名:

bool func( char );

std::string str;
std::find_if( str.begin(), str.end(), func ) )

在這種情況下,谷歌並不是我的朋友:(有人在這里嗎?

#include <iostream>
#include <string>
#include <algorithm>

bool func( char c ) {
    return c == 'x';
}

int main() {
    std::string str ="abcxyz";;
    std::string::iterator it = std::find_if( str.begin(), str.end(), func );
    if ( it != str.end() ) {
        std::cout << "found\n";
    }
    else {
        std::cout << "not found\n";
    }
}

如果你試圖在std :: string str找到單個字符c ,你可以使用std::find()而不是std::find_if() 而且,實際上,最好使用std::string的成員函數string::find()而不是<algorithm>的函數。

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
  std::string str = "abcxyz";
  size_t n = str.find('c');
  if( std::npos == n )
    cout << "Not found.";
  else
    cout << "Found at position " << n;
  return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM