持续完善 Pinda.cn 秒建营销活动 通过低代码 零代码的模式快速创建营销活动,欢迎使用 。

如何使用find_first_of() algorithm?

find() algorithm一次只能找一個條件,若要同時找多個條件,需使用find_first_of()。

find_first_of()允許我們將要找的條件先放到另外一個container中,然後一起搜尋,結果傳回第一個找到的iterator。

此範例中我們想找出第一個出現的母音,因為母音有aeiou,若用find(),就得搜尋5次,若用find_first_of(),只需一行就可找出第一個母音。

 1/* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : GenericAlgo_find_first_of.cpp
 5Compiler    : Visual C++ 8.0 / ISO C++
 6Description : Demo how to use find_first_of() algorithm
 7Release     : 12/14/2006 1.0
 8*/

 9#include <iostream>
10#include <algorithm>
11#include <string>
12
13using namespace std;
14int main() {
15  string s = "To be or not to be is a question";
16  string vowel = "aeiou";
17
18  // first vowel in s
19  cout << "First vowel in s " << endl;
20  {
21    string::iterator c = find_first_of(s.begin(), s.end(), vowel.begin(), vowel.end());
22    if (c != s.end()) cout << *<< endl;
23  }

24
25  cout << endl;
26
27  // All vowel in s using while(), more readable
28  cout << "All vowel in s using while()" << endl;
29  string::iterator s_begin = s.begin();
30  while(s_begin != s.end()) {
31    string::iterator c = find_first_of(s_begin, s.end(), vowel.begin(), vowel.end());
32    if (c != s.end()) {
33      cout << *c++ << " ";
34      s_begin = c;
35    }

36    else {
37      break;
38    }

39  }

40
41  cout << endl << endl;
42
43  // all vowel in s usng for, more compact
44  cout << "All vowel in s using for()" << endl;
45  for(string::iterator s_begin = s.begin(),c; s_begin != s.end(); s_begin = c) {
46    c = find_first_of(s_begin, s.end(), vowel.begin(), vowel.end());
47    if (c != s.end()) cout << *c++ << " "else break;
48  }

49
50  cout << endl << endl;
51
52  return 0;
53}


執行結果

First vowel in s
o

All vowel in s using while()
o e o o o e i a u e i o
 
All vowel in s using for()
o e o o o e i a u e i o

請按任意鍵繼續 . . 


21,22行為find_first_of的標準用法,有兩個input range。

我們似乎無法滿足若只能找到一個母音的結果,若我們想找到所有的母音呢?若找到第一個母音後,則繼續從找到的位置的下一個繼續找,依直到找不到為止,29行到39行使用while(),這種寫法可讀性較佳,也顯示了while()仍有其價值,44行到48行使用for(),程式較精簡,不過可讀性較差,需要一點程度。

posted @   工具人Kim哥  阅读(1465)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
持续完善 Pinda.cn 秒建营销活动 通过低代码 零代码的模式快速创建营销活动,欢迎使用 。
点击右上角即可分享
微信分享提示