代码之家  ›  专栏  ›  技术社区  ›  Patrick

使用std::find_if和std::string

  •  2
  • Patrick  · 技术社区  · 17 年前

    我在这里很愚蠢,但我无法获得谓词的函数签名,如果在字符串上迭代时:

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

    在这种情况下,谷歌不是我的朋友:(这里有人吗?

    2 回复  |  直到 17 年前
        1
  •  12
  •   anon anon    17 年前
    #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";
        }
    }
    
        2
  •  4
  •   John Dibling    17 年前

    如果你想找一个角色 c str 你可以用 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;
    }