C ++ set find()函数用于查找具有给定值 val 的元素。如果找到元素,则返回指向该元素的迭代器,否则返回指向集合末尾的迭代器,即set :: end()。
iterator find (const value_type& val) const; // C++ 11 之前 const_iterator find (const value_type& val) const; //从 C++ 11开始 iterator find (const value_type& val); //从 C++ 11开始
val:指定要在集合容器中搜索的值。
如果找到元素,则返回指向该元素的迭代器,否则返回指向集合末尾的迭代器,即set :: end()。
大小为对数。
没有变化。
容器被访问(const版本和非const版本)都不能修改容器。
没有访问映射的值:同时访问和修改元素是安全的。
如果引发异常,则容器中没有任何更改。
让我们看一个简单的示例,查找具有给定键值的元素:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<int> m = {100,200,300,400};
auto it = m.find(300);
cout << "迭代器指向 " << *it << endl;
return 0;
}输出:
迭代器指向 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() ) {
// 未找到元素
cout<<"未找到元素";
}
else {
// 找到
cout << "迭代器指向 " << *it<< endl;
}
return 0;
}输出:
未找到元素
在上面的示例中,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<<"输入要搜索的元素: ";
cin>>n;
auto search = example.find(n);
if (search != example.end()) {
cout << n<<" 找到并且值是 " << *search << '\n';
} else {
cout << n<<" 未找到\n";
}
}输出:
输入要搜索的元素: b 找到并且值是 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包含:";
for (it = myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}输出:
myset包含: 10 20 30 50 70 80 90 100