string中find()返回值是字母在母串中的位置(下标索引),如果没有找到,那么会返回一个特别的标记npos。(返回值可以看成是一个int型的数)
string sentence = "I am a bad girl";
char s = 'c';
if(string::npos == sentence.find(s)) cout << "不存在" << endl;
最简单的方式是对vector中的指定元素进行计数,如果count不为零,表示该元素存在,那么std::count可以很容易实现。
vector<string> words = {"wk","xf","ot","je"};
string word = "wk";
if(count(words.begin(), words.end(), word)) cout << "Found" << endl;
else cout << "Not Found" << endl;
较之count(),std::find()算法能够更快速的查找给定范围内的值,因为std::count()会变量整个容器以获得元素计数,而find()在找到匹配元素后就立即停止搜索。
vector<string> words = {"wk","xf","ot","je"};
string word = "wk";
if(find(words.begin(), words.end(), word)!=words.end()) cout << "Found" << endl;
else cout << "Not Found" << endl;
如果vector是有序的,那么可以考虑使用这种算法,如果在给定范围内找到元素,则返回true,否则返回false。该方式是采用二分法查找,时间复杂度为O(log(n)),速度比较快。
vector<string> words = {"wk","xf","ot","je"};
string word = "wk";
if(binary_search(words.begin(), words.end(), word)) cout << "Found" << endl;
else cout << "Not Found" << endl;