C++设置 find()函数用于查找具有给定值值的元素。如果找到该元素,则返回指向该元素的迭代器,否则,返回指向集合末尾的迭代器,即set::end()。
iterator find (const value_type& val) const; //until C++ 11 const_iterator find (const value_type& val) const; //since C++ 11 iterator find (const value_type& val); //since C++ 11
val :指定要在集合集合中搜索的值。
如果找到该元素,则返回指向该元素的迭代器,否则,返回指向集合末尾的迭代器,即set :: end()。
让我们看一个简单的示例,查找具有给定键值的元素:
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-set-find-function.html
来源:LearnFk无涯教程网
#include <iostream> #include <set> using namespace std; int main(void) { set<int> m = {100,200,300,400}; auto it = m.find(300); cout << "Iterator points to " << *it << endl; return 0; }
输出:
Iterator points to 300
让我们看一个简单的示例来查找元素:
#include <iostream> #include <set> using namespace std; int main(void) { set<char> m = {'a', 'b', 'c', 'd'}; auto it = m.find('e'); if ( it == m.end() ) { //not found cout<<"Element not found"; } else { //found cout << "Iterator points to " << *it<< endl; } return 0; }
输出:
Element not found
在上面的示例中,find()函数在集合m中查找键值e,如果在集合m中找不到键值e,则它将返回未找到消息,否则将显示集合。
让我们看一个简单的例子:
#include <iostream> #include <set> using namespace std; int main() { char n; set<char> example = {'a','b','c','d','e'}; cout<<"Enter the element which you want to search: "; cin>>n; auto search = example.find(n); if (search != example.end()) { cout << n<<" found and the value is " << *search << '\n'; } else { cout << n<<" not found\n"; } }
输出:
Enter the element which you want to search: b b found and the value is b
在上面的示例中,使用find()函数根据用户的给定值查找元素。
让我们看一个简单的例子:
#include <iostream> #include <set> int main () { std::set<int> myset; std::set<int>::iterator it; for (int i = 1; i <= 10; i++) myset.insert(i*10); it = myset.find(40); myset.erase (it); myset.erase (myset.find(60)); std::cout << "myset contains:"; for (it = myset.begin(); it!=myset.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; }
输出:
myset contains: 10 20 30 50 70 80 90 100
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)