C++ Set find()
C++ Set find()
C++ Set find()函数用于通过给定的查找元素 strong>值值如果找到元素,则返回指向该元素的迭代器,否则返回指向集合末尾的迭代器,即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()。
复杂度
大小为对数。
迭代器有效性
无变化。
Data Races
容器已被访问(const和非const版本均未修改容器。
未访问映射值: 同时访问和修改元素是安全。
异常安全性
如果引发异常,则容器中没有任何更改。
示例1
让我们看一个简单的示例,查找具有给定键值的元素:
#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;
}
输出:
示例2
让我们看一个简单的示例来查找元素:
#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;
}
输出:
在上面的示例中,find()函数在集合m中查找键值e,如果在集合m中找不到键值e,则将返回未找到消息,否则将显示集合。
示例3
让我们看一个简单的示例:
#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()函数根据用户给定的值查找元素。
示例4
让我们来看一个简单的例子例如:
#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